这里是Innocent React的问题
我有一个useEffect
方法,关闭escape
按键上的模态,在我的代码中重复了几次,看起来像这样:
const [shouldShowModal, setShouldShowModal] = useProfileModal();
useEffect(() => {
const closeModalOnEscape = (e: KeyboardEvent | any): void => {
if (e.key === "Escape") setShouldShowModal(false);
};
document.addEventListener("keydown", closeModalOnEscape);
return () => {
document.removeEventListener("keydown", closeModalOnEscape);
};
}, [setShouldShowModal]);
是否有一种方法可以定义useEffect
片跨多个组件使用?
只需定义一个自定义钩子,接受setter
const useCloseModalOnEscape = (setShouldShowModal) => {
useEffect(() => {
const closeModalOnEscape = (e: KeyboardEvent | any): void => {
if (e.key === "Escape") setShouldShowModal(false);
};
document.addEventListener("keydown", closeModalOnEscape);
return () => {
document.removeEventListener("keydown", closeModalOnEscape);
};
}, [setShouldShowModal]);
}
然后像这样使用:
const [shouldShowModal, setShouldShowModal] = useProfileModal();
useCloseModalOnEscape(setShouldShowModal);
您可以将setShouldShowModal
或useCloseModalOnEscape
重命名为对您的其他用例更准确的东西,如果它们不是全部在关闭情态的上下文中。
如果useProfileModal
的每个实例都将在转义时关闭,那么您应该将useEffect
(从useCloseModalOnEscape
的内部)包含在useProfileModal
中。
由于每次使用useProfileModal
都会使用该效果,因此只需将该效果放在useProfileModal
中即可。这样,每个组件中的代码只需要
const [shouldShowModal, setShouldShowModal] = useProfileModal();
and have, inuseProfileModal
:
const useProfileModal = () => {
// ...
useEffect(() => {
const closeModalOnEscape = (e: KeyboardEvent | any): void => {
if (e.key === "Escape") setShouldShowModal(false);
};
document.addEventListener("keydown", closeModalOnEscape);
return () => {
document.removeEventListener("keydown", closeModalOnEscape);
};
}, [setShouldShowModal]);
// ...
return [shouldShowModal, setShouldShowModal];