From 18786aee68dfd218fce7af23765a52c27434ca87 Mon Sep 17 00:00:00 2001 From: unix Date: Tue, 21 Apr 2020 13:32:02 +0800 Subject: [PATCH] fix(modal): fix onOpen not triggered when modal opening --- components/modal/modal-context.ts | 2 -- components/modal/modal.tsx | 24 +++++++++++------------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/components/modal/modal-context.ts b/components/modal/modal-context.ts index 0b6db51..fb97453 100644 --- a/components/modal/modal-context.ts +++ b/components/modal/modal-context.ts @@ -2,12 +2,10 @@ import React from 'react' export interface ModalConfig { close: () => void - open: () => void } const defaultContext = { close: () => {}, - open: () => {}, } export const ModalContext = React.createContext(defaultContext) diff --git a/components/modal/modal.tsx b/components/modal/modal.tsx index 015210d..ba9d53e 100644 --- a/components/modal/modal.tsx +++ b/components/modal/modal.tsx @@ -14,16 +14,13 @@ import useBodyScroll from '../utils/use-body-scroll' interface Props { disableBackdropClick?: boolean - onClose: () => void - onOpen: () => void + onClose?: () => void + onOpen?: () => void open?: boolean } const defaultProps = { disableBackdropClick: false, - onClose: () => {}, - onOpen: () => {}, - open: false, } type NativeAttrs = Omit, keyof Props> @@ -34,7 +31,7 @@ const Modal: React.FC> = React.memo(({ }) => { const portal = usePortal('modal') const [, setBodyHidden] = useBodyScroll() - const [visible, setVisible] = useState(open) + const [visible, setVisible] = useState(false) const [withoutActionsChildren, ActionsChildren] = pickChild(children, ModalAction) const hasActions = ActionsChildren && React.Children.count(ActionsChildren) > 0 @@ -42,17 +39,19 @@ const Modal: React.FC> = React.memo(({ setVisible(false) onClose && onClose() } - const openModal = () => { - setVisible(true) - - onOpen && onOpen() - } useEffect(() => { + if (open === undefined) return setVisible(open) setBodyHidden(open) + + if (open) { + onOpen && onOpen() + } else { + onClose && onClose() + } }, [open]) - + const closeFromBackdrop = () => { if (disableBackdropClick && hasActions) return closeModal() @@ -60,7 +59,6 @@ const Modal: React.FC> = React.memo(({ const modalConfig: ModalConfig = useMemo(() => ({ close: closeModal, - open: openModal, }), []) if (!portal) return null