需求描述
点击按钮用于检测鼠标是否命中按钮
代码实现
import React from 'react';
import {useState, useEffect, useRef} from 'react';// 封装一个hook用来检测当前点击事件是否在某个元素之外
function useClickOutSide(ref,cb) {useEffect(()=>{const handleClickOutside = (e) => {if(ref.current && ref.current !== e.target){cb(); }}document.addEventListener('click',handleClickOutside);return () => document.removeEventListener('click', handleClickOutside);},[cb, ref]);
}function Dialog() {const [visible, setVisible] = useState(false);const refObj = useRef(null);useClickOutSide(refObj,()=>{setVisible(false);} );return (<div><buttonref={refObj}onClick={() => {setVisible(true);}}>打开</button>{visible && <div className="dialog">我是弹框的内容</div>}</div>);
}export default Dialog;
效果
参考
React好玩的自定义hook-useClickOutSide_哔哩哔哩_bilibili