1 回答
TA贡献1883条经验 获得超3个赞
经过几个小时的搜索错误后我解决了它
const [open, setOpen] = useState(false);
const ref = useRef();
// on link click change open to false
useOutsideClick(ref, () => {
if (open) setOpen(false);
});
return (
<MobileMenuWrapper ref={ref}>
<BurgerIcon open={open} setOpen={setOpen} />
<MobileMenuList open={open} setOpen={setOpen}>
<MenuLinks />
</MobileMenuList>
</MobileMenuWrapper>
);
和钩子
export const useOutsideClick = (ref, callback) => {
const handleClick = (e) => {
if (ref.current && ref.current.contains(e.target)) {
callback();
}
};
useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
});
};
添加回答
举报