![](/img/trans.png)
[英]React Hook "useCustomHook" is called conditionally. React Hooks must be called in the exact same order in every component render
[英]React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render
我在控制台中收到此錯誤。 我該如何解決這個問題?
const modalRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (modalRef.current && !modalRef.current.contains(event.target)) {
close();
}
};
document.addEventListener("click", handleClickOutside);
return () => {
document.removeEventListener("click", handleClickOutside);
};
}, [close, modalRef]);
我正在嘗試使用 useEffect 掛鈎在模態打開時添加點擊事件偵聽器,並在模態關閉時將其刪除。 handleClickOutside 回調 function 應該在用戶單擊模態框外部時關閉模態框,方法是檢查 modalRef 元素是否包含點擊事件的目標元素。
好的,所以我得到了解決方案。 這里是。
useEffect(() => {
function handleClickOutside(event) {
if (modalRef.current && !modalRef.current.contains(event.target)) {
close();
}
}
document.addEventListener("click", handleClickOutside);
return () => {
document.removeEventListener("click", handleClickOutside);
};
}, []);
if (!props.show) {
return null;
}
```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.