简体   繁体   English

反应事件处理程序未删除

[英]React event handler not removed

I have a click event handler in my React component and wish to remove the event handler when hideLeft occurs, but am unable to do so with $(document).unbind('click', this.hideLeft.bind(this)) .我的 React 组件中有一个 click 事件处理程序,并希望在hideLeft发生时删除该事件处理程序,但我无法使用$(document).unbind('click', this.hideLeft.bind(this)) Currently can only remove the click event handler by doing $(document).unbind('click') .目前只能通过执行$(document).unbind('click')来删除点击事件处理程序。

How can I avoid this and only remove click event handlers associated with the hideLeft function?如何避免这种情况,只删除与hideLeft函数关联的点击事件处理程序?

class Header extends Component {
    constructor(props, context) {
        super(props, context); 
        this.state = {
            panel_visible: false
        };
    }

    logOut() {
        console.log('logged out');
    }

    hideLeft(event) {
        if (!$(event.target).closest('.menu').length) {
            $(document).unbind('click');                      
            this.setState({
                panel_visible: false
            }); 
        }
    }

    showLeft() {
        this.setState({
            panel_visible: true
        });
        $(document).bind('click', this.hideLeft.bind(this));    
    }


    render() {
       return (
               <Sticky>
                    <header className='app-header'>
                      <LeftPanel visibility={this.state.panel_visible} showLeft={e => this.showLeft()} 
                        hideLeft={e => this.hideLeft()} />
                      <button onClick={e => this.showLeft()}>Show Left Menu!</button>
                      <button className='btn btn-default logout' onClick={e => this.logOut()}>Log Out</button>
                      <h1>Some header </h1>
                    </header>
               </Sticky>
           );
    }
}

I'm doing this using vanilla js methods addEventListener and removeEventListener .我正在使用 vanilla js 方法addEventListenerremoveEventListener这样做。

adding添加

document.addEventListener('click', this.hideLeft.bind(this));

removing:去除:

document.removeEventListener('click', this.hideLeft.bind(this));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM