2015-10-16 250 views
0

我在React组件中有一个单击事件处理程序,并希望在hideLeft发生时删除事件处理程序,但无法使用$(document).unbind('click', this.hideLeft.bind(this))。目前只能通过执行$(document).unbind('click')来移除点击事件处理程序。未删除React事件处理程序

我该如何避免这种情况,只能删除与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> 
      ); 
    } 
} 
+0

我不知道是什么反应代码是在这里?渲染方法似乎是空白的,事件处理程序通常可以通过反应代码来处理,而不是使用jquery。 – noveyak

+0

嗨@noveyak,我省略了渲染方法的简单性,因为事件处理程序与渲染方法无关 –

回答

1

我使用香草JS方法addEventListenerremoveEventListener这样做。

加入

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

删除:

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