![](/img/trans.png)
[英]Reactjs - Higher Order Component / findDOMNode not working correctly
[英]Reactjs - Higher Order Component unmount not working correctly
我創建了一個HOC來監聽其包裝組件之外的點擊,以便包裝組件可以根據需要進行監聽和響應。
HOC看起來像這樣:
const addOutsideClickListener = (WrappedComponent) => {
class wrapperComponent extends React.Component {
componentDidMount() {
console.log('*** component did MOUNT called ***');
document.addEventListener('click', this._handleClickOutside.bind(this), true);
}
componentWillUnmount() {
console.log('*** component will UNMOUNT called ***');
document.removeEventListener('click', this._handleClickOutside.bind(this), true);
}
_handleClickOutside(e) {
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;
}
它工作得很好......大部分時間。
卸載包裝組件時,會調用方法“componentWillUnmount”,但“removeEventListener”繼續偵聽事件,因此我收到錯誤消息“Uncaught Error:在已卸載的組件上調用了findDOMNode”。
可能導致這種情況的任何想法?
您的removeEventListener
無法正常工作的原因是您嘗試刪除新創建的函數。 這同樣適用於addEventListener
。 這是兩個完全不同的功能,彼此之間沒有任何參考。
你必須綁定你的方法_handleClickOutside
以便React知道它的一個版本。 你可以通過在構造函數中綁定它來實現
constructor() {
super();
this._handleClickOutside.bind(this);
}
或使用ES6箭頭方法自動綁定它
_handleClickOutside = (e) => { ... }
現在,您將綁定方法傳遞給eventlisteners
document.addEventListener('click', this._handleClickOutside, true);
和分別刪除監聽器。
將其添加到構造函數:
this._handleClickOutside = this._handleClickOutside.bind(this)
然后這樣做:
componentDidMount() {
document.addEventListener('click', this._handleClickOutside, true);
}
componentWillUnmount() {
document.removeEventListener('click', this._handleClickOutside, true);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.