[英]Reactjs - Higher Order Component / findDOMNode not working correctly
我创建了一个HOC来监听其包装组件外部的点击,以便包装组件可以根据需要进行监听和响应。
HOC如下所示:
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;
}
每当我在任何地方单击时,都会在_handleOutsideClick回调上收到错误“未捕获的错误:元素似乎既不是ReactComponent也不是DOMNode”。
任何想法可能是什么原因造成的?
更新:
好的,所以错误的根源是_handleClickOutside中的“ this”现在指向“文档”,这是预期的https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener #the_value_of_this_within_the_handler
这看起来绝对是一团糟-看来我可以正确绑定事件,但无法解除绑定,或者我可以正确解除绑定,但是绑定方法将引发错误...
尝试使用-
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);
}
或对_handleClickOutside
使用箭头功能。
_handleClickOutside = (e) => {
// 'this' here refers to document ???
const domNode = ReactDOM.findDOMNode(this);
if ((!domNode || !domNode.contains(e.target))) {
this.wrapped.handleClickOutside();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.