简体   繁体   中英

How to handle event when clicking outside of component?

I reactjs I have a component and it has this code to detect whether there is a click outside the component:

export class Cart extends React.Component {
handleClick(e) {
            if (!ReactDOM.findDOMNode(this).contains(e.target)) {
                console.log('testing=e.target', e.target)
            }
}

componentWillMount() {
            document.addEventListener('click', this.handleClick, false);
}

componentWillUnmount() {
            document.removeEventListener('click', this.handleClick, false);
}

render()
{
   return (<div>hello</div>)
}}

However I am getting an error in the findDOMNode statement:

Uncaught Error: Element appears to be neither ReactComponent nor DOMNode 

How can I fix this?

You can add id property to the div component, and then refactor the code as follows:

export class Cart extends React.Component {
  handleClick(e) {
    if (e.target.id === 'div') {
      console.log('inside')
    } else {
      console.log('outside!')
    }
  }

  componentWillMount() {
    document.addEventListener('click', this.handleClick, false);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleClick, false);
  }

  render()
  {
    return (
      <div id="div">
        hello
      </div>)
  }
}

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