diff --git a/examples/switch.tsx b/examples/switch.tsx index c918c8a..5339e88 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 ad45d4a..6ab1881 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); } } });