From cdae0559af4f7056ab6688a49627db874ec051f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=8C=E8=B4=A7=E6=9C=BA=E5=99=A8=E4=BA=BA?= Date: Tue, 5 Nov 2024 11:35:06 +0800 Subject: [PATCH] fix: take margin into account --- examples/switch.tsx | 1 + src/hooks/useHeights.tsx | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/examples/switch.tsx b/examples/switch.tsx index c918c8ae..5339e887 100644 --- a/examples/switch.tsx +++ b/examples/switch.tsx @@ -16,6 +16,7 @@ const MyItem: React.FC = ({ id }, ref) => ( lineHeight: '30px', boxSizing: 'border-box', display: 'inline-block', + // marginBottom: 8, }} > {id} diff --git a/src/hooks/useHeights.tsx b/src/hooks/useHeights.tsx index ad45d4a2..6ab1881c 100644 --- a/src/hooks/useHeights.tsx +++ b/src/hooks/useHeights.tsx @@ -1,10 +1,15 @@ -import * as React from 'react'; -import { useRef, useEffect } from 'react'; import findDOMNode from 'rc-util/lib/Dom/findDOMNode'; import raf from 'rc-util/lib/raf'; +import * as React from 'react'; +import { useEffect, useRef } from 'react'; import type { GetKey } from '../interface'; import CacheMap from '../utils/CacheMap'; +function parseNumber(value: string) { + const num = parseFloat(value); + return isNaN(num) ? 0 : num; +} + export default function useHeights( getKey: GetKey, onItemAdd?: (item: T) => void, @@ -32,8 +37,14 @@ export default function useHeights( if (element && element.offsetParent) { const htmlElement = findDOMNode(element); const { offsetHeight } = htmlElement; - if (heightsRef.current.get(key) !== offsetHeight) { - heightsRef.current.set(key, htmlElement.offsetHeight); + const { marginTop, marginBottom } = getComputedStyle(htmlElement); + + const marginTopNum = parseNumber(marginTop); + const marginBottomNum = parseNumber(marginBottom); + const totalHeight = offsetHeight + marginTopNum + marginBottomNum; + + if (heightsRef.current.get(key) !== totalHeight) { + heightsRef.current.set(key, totalHeight); } } });