import type { EmptyProps } from 'antd'; import { Empty } from 'antd'; import type { ReactNode } from 'react'; import React, { useEffect, useRef, useState } from 'react'; export interface AutoEmptyProps extends EmptyProps { /** * @description 显示内容 */ children?: React.ReactNode; noEmptyRender?: () => ReactNode; } const AutoEmpty = (props: AutoEmptyProps) => { const { children, noEmptyRender, ...emptyProps } = props; const [empty, setEmpty] = useState(undefined); const wrapperRef = useRef(null); const observerRef = useRef(); useEffect(() => { if (!wrapperRef.current) return; setEmpty(!wrapperRef.current?.hasChildNodes()); observerRef.current = new MutationObserver(() => { const hasChildren = wrapperRef.current?.hasChildNodes(); setEmpty(!hasChildren); }); observerRef.current.observe(wrapperRef.current, { childList: true, // 监控直接子节点 subtree: true, // 监控所有后代 characterData: true, // 监控文本变化 }); return () => observerRef.current?.disconnect(); }, []); return ( <>
{empty === false && noEmptyRender?.()} {children}
{empty && } ); }; export default AutoEmpty;