import React, { PropsWithChildren, useEffect, useMemo, useRef, useState, } from 'react'; interface AutoFolderProps extends PropsWithChildren { maxHeight: number; showFullText?: React.ReactNode; backgroundColor?: string; } export const AutoFolder: React.FC = React.memo((props) => { const { maxHeight, showFullText = 'More', backgroundColor = 'white' } = props; const [isShowFull, setIsShowFull] = useState(false); const contentRef = useRef(null); const observer = useMemo( () => new window.ResizeObserver((entries) => { if (entries[0]) { const { height } = entries[0].contentRect; if (height > maxHeight) { setIsShowFull(false); observer.disconnect(); // 触发一次则解除连接 } else { setIsShowFull(true); } } }), [] ); useEffect(() => { if (!contentRef.current) { return; } observer.observe(contentRef.current); return () => { observer.disconnect(); }; }, []); return (
{props.children}
{!isShowFull && (
setIsShowFull(true)} > {showFullText}
)}
); }); AutoFolder.displayName = 'AutoFolder';