From b086739199d4918ea7f53e3a91e4e44b493ce14e Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Fri, 20 May 2022 23:03:21 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BF=AE=E6=94=B9AutoFolder?= =?UTF-8?q?=E7=9A=84=E9=80=BB=E8=BE=91=E4=BB=A5=E6=94=AF=E6=8C=81=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E7=BB=84=E4=BB=B6=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../design/components/AutoFolder/index.tsx | 38 ++++++++++++++----- packages/design/components/index.ts | 1 + 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/packages/design/components/AutoFolder/index.tsx b/packages/design/components/AutoFolder/index.tsx index 5d0f1c69..d4000c40 100644 --- a/packages/design/components/AutoFolder/index.tsx +++ b/packages/design/components/AutoFolder/index.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useRef, useState } from 'react'; +import React, { useEffect, useMemo, useRef, useState } from 'react'; interface AutoFolderProps { maxHeight: number; @@ -12,22 +12,40 @@ export const AutoFolder: React.FC = React.memo((props) => { backgroundColor = 'rgba(0,0,0,0)', } = props; const [isShowFull, setIsShowFull] = useState(false); - const contentRef = useRef(); + 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) { - if (contentRef.current.scrollHeight > maxHeight) { - setIsShowFull(false); - } else { - setIsShowFull(true); - } + if (!contentRef.current) { + return; } - }, [props.maxHeight]); + observer.observe(contentRef.current); + + return () => { + observer.disconnect(); + }; + }, []); return (