简体   繁体   中英

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)) . Currently can only remove the click event handler by doing $(document).unbind('click') .

How can I avoid this and only remove click event handlers associated with the hideLeft function?

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 .

adding

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

removing:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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