Detect click outside React component

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

    Typescript with Hooks

    Note: I'm using React version 16.3, with React.createRef. For other versions use the ref callback.

    Dropdown component:

    interface DropdownProps {
     ...
    };
    
    export const Dropdown: React.FC () {
      const ref: React.RefObject = React.createRef();
      
      const handleClickOutside = (event: MouseEvent) => {
        if (ref && ref !== null) {
          const cur = ref.current;
          if (cur && !cur.contains(event.target as Node)) {
            // close all dropdowns
          }
        }
      }
    
      useEffect(() => {
        // Bind the event listener
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
          // Unbind the event listener on clean up
          document.removeEventListener("mousedown", handleClickOutside);
        };
      });
    
      return (
        
    ...
    ); }

提交回复
热议问题