Detect click outside React component

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

    To extend on the accepted answer made by Ben Bud, if you are using styled-components, passing refs that way will give you an error such as "this.wrapperRef.contains is not a function".

    The suggested fix, in the comments, to wrap the styled component with a div and pass the ref there, works. Having said that, in their docs they already explain the reason for this and the proper use of refs within styled-components:

    Passing a ref prop to a styled component will give you an instance of the StyledComponent wrapper, but not to the underlying DOM node. This is due to how refs work. It's not possible to call DOM methods, like focus, on our wrappers directly. To get a ref to the actual, wrapped DOM node, pass the callback to the innerRef prop instead.

    Like so:

     { this.el = el }} />
    

    Then you can access it directly within the "handleClickOutside" function:

    handleClickOutside = e => {
        if (this.el && !this.el.contains(e.target)) {
            console.log('clicked outside')
        }
    }
    

    This also applies for the "onBlur" approach:

    componentDidMount(){
        this.el.focus()
    }
    blurHandler = () => {
        console.log('clicked outside')
    }
    render(){
        return(
             { this.el = el }}
            />
        )
    }
    

提交回复
热议问题