Detect click outside React component

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

    [Update] Solution with React ^16.8 using Hooks

    CodeSandbox

    import React, { useEffect, useRef, useState } from 'react';
    
    const SampleComponent = () => {
        const [clickedOutside, setClickedOutside] = useState(false);
        const myRef = useRef();
    
        const handleClickOutside = e => {
            if (!myRef.current.contains(e.target)) {
                setClickedOutside(true);
            }
        };
    
        const handleClickInside = () => setClickedOutside(false);
    
        useEffect(() => {
            document.addEventListener('mousedown', handleClickOutside);
            return () => document.removeEventListener('mousedown', handleClickOutside);
        });
    
        return (
            
        );
    };
    
    export default SampleComponent;
    

    Solution with React ^16.3:

    CodeSandbox

    import React, { Component } from "react";
    
    class SampleComponent extends Component {
      state = {
        clickedOutside: false
      };
    
      componentDidMount() {
        document.addEventListener("mousedown", this.handleClickOutside);
      }
    
      componentWillUnmount() {
        document.removeEventListener("mousedown", this.handleClickOutside);
      }
    
      myRef = React.createRef();
    
      handleClickOutside = e => {
        if (!this.myRef.current.contains(e.target)) {
          this.setState({ clickedOutside: true });
        }
      };
    
      handleClickInside = () => this.setState({ clickedOutside: false });
    
      render() {
        return (
          
        );
      }
    }
    
    export default SampleComponent;
    

提交回复
热议问题