Detect click outside React component

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

    https://stackoverflow.com/a/42234988/9536897 it's not work on mobile mode.

    than you can try:

      // returns true if the element or one of its parents has the class classname
      hasSomeParentTheClass(element, classname) {
        if(element.target)
        element=element.target;
        
        if (element.className&& element.className.split(" ").indexOf(classname) >= 0) return true;
        return (
          element.parentNode &&
          this.hasSomeParentTheClass(element.parentNode, classname)
        );
      }
    
      componentDidMount() {
        const fthis = this;
    
        $(window).click(function (element) {
          if (!fthis.hasSomeParentTheClass(element, "myClass"))
            fthis.setState({ pharmacyFocus: null });
        });
      }
    
    • On the view, gave className to your specific element.

提交回复
热议问题