Detect click outside React component

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

    Here is my approach (demo - https://jsfiddle.net/agymay93/4/):

    I've created special component called WatchClickOutside and it can be used like (I assume JSX syntax):

    
      
    
    

    Here is code of WatchClickOutside component:

    import React, { Component } from 'react';
    
    export default class WatchClickOutside extends Component {
      constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
      }
    
      componentWillMount() {
        document.body.addEventListener('click', this.handleClick);
      }
    
      componentWillUnmount() {
        // remember to remove all events to avoid memory leaks
        document.body.removeEventListener('click', this.handleClick);
      }
    
      handleClick(event) {
        const {container} = this.refs; // get container that we'll wait to be clicked outside
        const {onClickOutside} = this.props; // get click outside callback
        const {target} = event; // get direct click event target
    
        // if there is no proper callback - no point of checking
        if (typeof onClickOutside !== 'function') {
          return;
        }
    
        // if target is container - container was not clicked outside
        // if container contains clicked target - click was not outside of it
        if (target !== container && !container.contains(target)) {
          onClickOutside(event); // clicked outside - fire callback
        }
      }
    
      render() {
        return (
          
    {this.props.children}
    ); } }

提交回复
热议问题