diff --git a/src/popover/Popover.tsx b/src/popover/Popover.tsx index 69b36226d8..907806c1ae 100644 --- a/src/popover/Popover.tsx +++ b/src/popover/Popover.tsx @@ -1,4 +1,4 @@ -import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react'; +import React, { useState, useMemo, useCallback, useEffect, useRef, useLayoutEffect } from 'react'; import classNames from 'classnames'; import { debounce, isUndefined } from 'lodash'; import { usePopper } from 'react-popper'; @@ -26,7 +26,6 @@ const Popover = (props: PopoverProps) => { const prefixCls = usePrefixCls('popover-new', customPrefixCls); const [visible, setVisible] = useState(defaultVisible); const overContentRef = useRef(false); - const referenceElement = useRef(null); const popperElement = useRef(null); const arrowElement = useRef(null); @@ -65,6 +64,28 @@ const Popover = (props: PopoverProps) => { }, [onVisibleChange, enterVisible, enterable] ); + const onDocumentClick = useCallback( + (event: MouseEvent) => { + const { target } = event; + if (!referenceElement.current?.contains(target as Node) && !popperElement.current?.contains(target as Node)) { + updateVisible(false); + } + }, + [updateVisible] + ); + + useEffect(() => { + if (!isUndefined(enterVisible)) { + setVisible(enterVisible); + } + }, [enterVisible]); + + useLayoutEffect(() => { + document.addEventListener('mousedown', onDocumentClick); + return () => { + document.removeEventListener('mousedown', onDocumentClick); + }; + }, [onDocumentClick]); const isClickToShow = useMemo(() => trigger.indexOf('click') !== -1, [trigger]); @@ -124,12 +145,6 @@ const Popover = (props: PopoverProps) => { return roles; }, [isClickToShow, isFocusToShow, isHoverToShow, onClick, onFocus, onBlur, onMouseEnter, onMouseLeave]); - useEffect(() => { - if (!isUndefined(enterVisible)) { - setVisible(enterVisible); - } - }, [enterVisible]); - return ( <>
diff --git a/src/popover/demos/Popover.stories.tsx b/src/popover/demos/Popover.stories.tsx index b8a3b437cb..81e46a353c 100644 --- a/src/popover/demos/Popover.stories.tsx +++ b/src/popover/demos/Popover.stories.tsx @@ -144,6 +144,7 @@ const ControlTemplate: Story = (args) => { const show = () => setVisible(true); const hide = () => setVisible(false); const onVisibleChange = (resetVisible: boolean) => { + setVisible(resetVisible); console.log(resetVisible); }; @@ -178,7 +179,7 @@ const ControlTemplate: Story = (args) => { - +