Detect click outside React component

后端 未结 30 1226
日久生厌
日久生厌 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:14

    I did this partly by following this and by following the React official docs on handling refs which requires react ^16.3. This is the only thing that worked for me after trying some of the other suggestions here...

    class App extends Component {
      constructor(props) {
        super(props);
        this.inputRef = React.createRef();
      }
      componentWillMount() {
        document.addEventListener("mousedown", this.handleClick, false);
      }
      componentWillUnmount() {
        document.removeEventListener("mousedown", this.handleClick, false);
      }
      handleClick = e => {
        /*Validating click is made inside a component*/
        if ( this.inputRef.current === e.target ) {
          return;
        }
        this.handleclickOutside();
      };
      handleClickOutside(){
        /*code to handle what to do when clicked outside*/
      }
      render(){
        return(
          
    ) } }

提交回复
热议问题