我有一个用于管理模态状态的自定义钩子,我还通过上下文向下传递了showModal
和toggleModal
。 MainModal
组件接收内容并使用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通用模态,用于接收内容并呈现当前模态。 EntryModal
或DeleteModal
。 Styled.Modal
是antd
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>