Detect click outside React component

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

    I found a solution thanks to Ben Alpert on discuss.reactjs.org. The suggested approach attaches a handler to the document but that turned out to be problematic. Clicking on one of the components in my tree resulted in a rerender which removed the clicked element on update. Because the rerender from React happens before the document body handler is called, the element was not detected as "inside" the tree.

    The solution to this was to add the handler on the application root element.

    main:

    window.__myapp_container = document.getElementById('app')
    React.render(, window.__myapp_container)
    

    component:

    import { Component, PropTypes } from 'react';
    import ReactDOM from 'react-dom';
    
    export default class ClickListener extends Component {
    
      static propTypes = {
        children: PropTypes.node.isRequired,
        onClickOutside: PropTypes.func.isRequired
      }
    
      componentDidMount () {
        window.__myapp_container.addEventListener('click', this.handleDocumentClick)
      }
    
      componentWillUnmount () {
        window.__myapp_container.removeEventListener('click', this.handleDocumentClick)
      }
    
      /* using fat arrow to bind to instance */
      handleDocumentClick = (evt) => {
        const area = ReactDOM.findDOMNode(this.refs.area);
    
        if (!area.contains(evt.target)) {
          this.props.onClickOutside(evt)
        }
      }
    
      render () {
        return (
          
    {this.props.children}
    ) } }

提交回复
热议问题