1 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
經(jīng)過(guò)幾個(gè)小時(shí)的搜索錯(cuò)誤后我解決了它
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);
};
});
};
添加回答
舉報(bào)