如果用户在之外单击,则会关闭一个模式。
处理一种-传递isModalOpened,因此只有在isModalOpened为true时,点击状态才会更新。

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]);
处理两种-从dep数组中删除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的值不会在函数中包含变量,从而根本不需要依赖项。

10-08 08:12