【react】Click on the blank space to hide

need

  • A div pop-up box, which is displayed when the button is clicked and hidden when the blank space is clicked.
  • Bind hidden event on document
  • Clicking on the displayed button requires preventing bubbling
  • Use e.stopPropagation(); invalid

code

// 对应的按钮添加阻止冒泡
<div onClick={
    
    (e) => {
    
    
     e.nativeEvent.stopImmediatePropagation();
     handleSetActiveBtn(item)
}}></div>;

Encapsulation hooks

import {
    
     RefObject, useEffect } from "react";

const useClickOutside = (ref: RefObject<HTMLElement>, handler: Function) => {
    
    
    useEffect(() => {
    
    
        const listener = (event: MouseEvent) => {
    
    
            if (!ref.current || ref.current.contains(event.target as HTMLElement)) {
    
    
                return;
            }
            handler(event);
        };
        document.addEventListener("click", listener);
        return () => {
    
    
            document.removeEventListener("click", listener);
        };
    }, [ref, handler]);
};

export default useClickOutside;

divs that need to be shown/hidden

{
    
    
  backgroundColorVisible && 
   <div onClick={
    
    e => e.nativeEvent.stopImmediatePropagation()} ref={
    
    bgColorRef}>
     <SketchPicker className="stage-color-setting"}
     	color={
    
    backgroundColor}
     	onChangeComplete={
    
    onHandleBackgroundColor} />
   </div>
}

const bgColorRef = useRef<HTMLDivElement>(null);
useClickOutside(bgColorRef, () => {
    
    
  setBackgroundColorVisible(false);
});

Guess you like

Origin blog.csdn.net/qq_43585322/article/details/132762406
Recommended