typescript React>定义要跨组件使用的通用效果

nwlqm0z1  于 2022-12-05  发布在  TypeScript
关注(0)|答案(3)|浏览(128)

无辜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片段以跨多个组件使用?

k3bvogb1

k3bvogb11#

只需定义一个接受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);

您可以重命名setShouldShowModaluseCloseModalOnEscape,使其更准确地适应其他用例,如果它们并不都在关闭模态的上下文中的话。
如果useProfileModal的每个示例都将在转义时关闭,那么您应该在useProfileModal中包含useEffect(来自useCloseModalOnEscape内部)。

u5i3ibmn

u5i3ibmn2#

因为每次使用useProfileModal都会用到这个效果,所以只需将这个效果放在useProfileModal中。

const [shouldShowModal, setShouldShowModal] = useProfileModal();

且在useProfileModal中具有:

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];
rkkpypqq

rkkpypqq3#

可以,useEffect代码可以定义为一个单独的函数,然后从多个组件调用。

// Define a custom hook to handle the keydown event
function useCloseModalOnEscape(toggleModal) {
  useEffect(() => {
    const closeModalOnEscape = (e: KeyboardEvent | any): void => {
      if (e.key === "Escape") toggleModal({ shouldShowModal: false });
    };
    document.addEventListener("keydown", closeModalOnEscape);
    return () => {
      document.removeEventListener("keydown", closeModalOnEscape);
    };
  }, [toggleModal]);
}

// Define a component that uses the custom hook
function MyComponent() {
  const [{ shouldShowModal, profile }, toggleModal] = useProfileModal();

  // Call the custom hook to handle the keydown event
  useCloseModalOnEscape(toggleModal);

  // Other component code...
}

useCloseModalOnEscape函数是一个自定义挂钩,它将toggleModal函数作为参数并处理keydown事件。MyComponent组件使用useProfileModal挂钩来获取toggleModal函数,然后调用'useClose

相关问题