import React, { PropsWithChildren, useEffect, useMemo, useRef, useState, } from 'react'; import { useMemoizedFn } from 'ahooks'; interface AutoFolderProps extends PropsWithChildren { maxHeight: number; showFullText?: React.ReactNode; backgroundColor?: string; } export const AutoFolder: React.FC = React.memo((props) => { const { showFullText = 'More', backgroundColor = 'white' } = props; const [isShowFullBtn, setIsShowFullBtn] = useState(false); // 是否显示展示所有内容的按钮 const [isShowFull, setIsShowFull] = useState(false); // 是否点击按钮展示所有 const contentRef = useRef(null); useEffect(() => { if (!contentRef.current) { return; } const observer = new window.ResizeObserver((entries) => { if (entries[0]) { const { height } = entries[0].contentRect; if (height > maxHeight) { setIsShowFull(false); setIsShowFullBtn(true); observer.disconnect(); // 触发一次则解除连接 } } }); observer.observe(contentRef.current); return () => { observer.disconnect(); }; }, []); const maxHeight = useMemo(() => { if (isShowFull) { return 'none'; } else { return props.maxHeight; } }, [isShowFull, props.maxHeight]); const handleClickShowFullBtn = useMemoizedFn(() => { setIsShowFullBtn(false); setIsShowFull(true); }); return (
{props.children}
{isShowFullBtn && (
{showFullText}
)}
); }); AutoFolder.displayName = 'AutoFolder';