如果用户在之外单击,则会关闭一个模式。
处理一种-传递isModalOpened
,因此只有在isModalOpened
为true时,点击状态才会更新。
处理两种-从dep数组中删除const [isModalOpened, toggleModal] = useState(false);
const ref = useRef(null);
const clickOut = (e) => {
if (!ref.current.contains(e.target) && isModalOpened) {
toggleModal(false);
}
};
React.useEffect(() => {
window.addEventListener('mousedown', clickOut);
return () => {
window.removeEventListener('mousedown', clickOut);
};
}, [isModalOpened]);
isModalOpened
。
问题:是否应该将const [isModalOpened, toggleModal] = useState(false);
const ref = useRef(null);
const clickOut = (e) => {
if (!ref.current.contains(e.target)) {
toggleModal(false);
}
};
React.useEffect(() => {
window.addEventListener('mousedown', clickOut);
return () => {
window.removeEventListener('mousedown', clickOut);
};
}, []);
isModalOpened
传递给dep数组?
最佳答案
您不需要它。
原因是,如果将toggleModal
设置为相同的false
值,则不会导致重新渲染。
因此,您无需防范isModalOpened
的值,而ojit_code的值不会在函数中包含变量,从而根本不需要依赖项。