![](/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.