Detect click outside React component

后端 未结 30 1530
日久生厌
日久生厌 2020-11-22 13:54

I\'m looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the target from a click e

30条回答
  •  情深已故
    2020-11-22 14:24

    componentWillMount(){
    
      document.addEventListener('mousedown', this.handleClickOutside)
    }
    
    handleClickOutside(event) {
    
      if(event.path[0].id !== 'your-button'){
         this.setState({showWhatever: false})
      }
    }
    

    Event path[0] is the last item clicked

提交回复
热议问题