Antd模态不响应自定义钩子状态更改

时间:2020-10-05 15:55:16

标签: reactjs typescript antd

我有一个用于管理模态状态的自定义钩子,我还通过上下文向下传递了showModaltoggleModalMainModal组件接收内容并使用props.children

进行渲染

简化的演示 https://codesandbox.io/s/httpsstackoverflowcomquestions64212090-modal-antd-xptfv

useMainModal挂钩

export const useMainModal = () => {
  const [showModal, setShowModal] = useState<{ modalName: EntryModalEnum; visible: boolean }>({
    modalName: EntryModalEnum.deleteEntry,
    visible: false,
  });
  const [newsId, setNewsId] = useState<number | undefined>(undefined);

  const toggleModal = (type: EntryModalEnum) => {
    setShowModal({ modalName: type, visible: !showModal.visible });
  };

  const setId = (id: number) => {
    setNewsId(id);
  };

  return {
    showModal,
    toggleModal,
    newsId,
    setId,
  };
};

MainModal.tsx通用模态,用于接收内容并呈现当前模态。 EntryModalDeleteModalStyled.Modalantd Modal组件

export const MainModal = ({ children }: { children: React.ReactNode }) => {
  const modalRoot = document.querySelector('#modal-root');
  const { showModal } = useMainModal();

  if (!modalRoot) {
    return null;
  }

  return ReactDOM.createPortal(
    <Styled.Modal visible={showModal.visible} footer={null} destroyOnClose={true}>
      {children}
    </Styled.Modal>,
    modalRoot,
  );
};

我想使用通用的MainModal组件在首页中呈现这种模态。

<MainModal>
  <EntryModal />
</MainModal>

<MainModal>
  <DeleteModal />
</MainModal>

0 个答案:

没有答案