Javascript Reactjs-高阶组件/findDOMNode工作不正常
我创建了一个HOC来监听其包装组件外部的点击,以便包装组件可以监听并根据需要做出反应 HOC的外观如下所示:Javascript Reactjs-高阶组件/findDOMNode工作不正常,javascript,reactjs,react-jsx,Javascript,Reactjs,React Jsx,我创建了一个HOC来监听其包装组件外部的点击,以便包装组件可以监听并根据需要做出反应 HOC的外观如下所示: const addOutsideClickListener = (WrappedComponent) => { class wrapperComponent extends React.Component { constructor() { super(); this._handleClickOutside
const addOutsideClickListener = (WrappedComponent) => {
class wrapperComponent extends React.Component {
constructor() {
super();
this._handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener('click', this._handleClickOutside, true);
}
componentWillUnmount() {
document.removeEventListener('click', this._handleClickOutside, true);
}
_handleClickOutside(e) {
// 'this' here refers to document ???
const domNode = ReactDOM.findDOMNode(this);
if ((!domNode || !domNode.contains(e.target))) {
this.wrapped.handleClickOutside();
}
}
render() {
return (
<WrappedComponent
ref={(wrapped) => { this.wrapped = wrapped }}
{...this.props}
/>
);
}
}
return wrapperComponent;
}
无论何时单击任意位置,都会得到错误uncaughterror:Element在_handleOutsideClick回调上既不是ReactComponent也不是DOMNode
你知道这是什么原因吗
更新:
好的,所以错误的来源是这个inside _handleClickOutside现在指的是“document”,这是预期的
这看起来是一个绝对的混乱-似乎我可以正确绑定事件但无法解除绑定,或者我可以正确解除绑定但绑定方法将抛出错误…尝试使用此-
constructor() {
super();
this._handleClickOutsideRef = this._handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener('click', this._handleClickOutsideRef, true);
}
componentWillUnmount() {
document.removeEventListener('click', this._handleClickOutsideRef, true);
}
装订必须这样做-
constructor() {
super();
this._handleClickOutside = this._handleClickOutside.bind(this);
}
或使用箭头功能来显示_handleclickout
事实上,这会删除组件上的所有单击绑定,这没有帮助。我只需要删除有问题的绑定…之后将创建一个新的函数引用。将调用bind签出我的更新解决方案
_handleClickOutside = (e) => {
// 'this' here refers to document ???
const domNode = ReactDOM.findDOMNode(this);
if ((!domNode || !domNode.contains(e.target))) {
this.wrapped.handleClickOutside();
}
}