简体   繁体   中英

this.node.contains does not work if this.node is a ref to react component

There is XYZ component which I don't have access to. Now I want to detect if that component is clicked.

render () {
   return(
    <XYZ className="abc" ref={node => {this.pop = node}} /> // Note, I don't have access to XYZ component
  )}

Reading through various articals I found this:

handleClickOutside(e){
    if (this.pop.contains(e.target)){
         // not clicked outside
    }
}

I am getting Contains is undefined as this.pop is a React component . How to solve this?

You can use ReactDOM.findDOMNode to get a reference to the DOM node -

handleClickOutside(e) {
    if(this.pop) {
        const domNode = ReactDOM.findDOMNode(this.pop)
        if(this.pop.contains(e.target)) {
            //
        }
    }
}

Since findDOMNode is deprecated in React 16 and would be removed in future versions - another thing you can try is wrapping the XYZ component inside a div and check for click on that div.

render () {
   return(
    <div onClick={this.handleContainerClick}>
      <XYZ className="abc" ref={node => {this.pop = node}} /> // Note, I don't have access to XYZ component
    </div>
  )}
}

The current answer is to use the current attribute.

myRef = React.createRef();

const checkIfContains = e => {
    if (myRef.current.contains(e.target)) {
        doSomething();
    }
}

<div ref={myRef} onClick={checkIfContains} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM