【react】点击空白处隐藏

需求

  • 一个div弹框,点击按钮时显示,点击空白处隐藏
  • 在document上绑定隐藏事件
  • 点击显示的按钮需要阻止冒泡
  • 使用e.stopPropagation();失效

代码

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

封装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;

需要显示/隐藏的div

{
  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);
});

你可能感兴趣的:(前端,react,react.js,前端)