[英]React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render
I get this error in my console.我在控制台中收到此错误。 How can I solve this?我该如何解决这个问题?
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]);
I'm trying to use the useEffect hook to add the click event listener when the modal is open, and remove it when the modal is closed.我正在尝试使用 useEffect 挂钩在模态打开时添加点击事件侦听器,并在模态关闭时将其删除。 The handleClickOutside callback function should close the modal when the user clicks outside of it, by checking if the modalRef element contains the target element of the click event. handleClickOutside 回调 function 应该在用户单击模态框外部时关闭模态框,方法是检查 modalRef 元素是否包含点击事件的目标元素。
Okay so I got the solution.好的,所以我得到了解决方案。 Here it is.这里是。
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.