Skip to content

Commit 9570abd

Browse files
authored
fix: take margin into account (#291)
1 parent 8ff44e2 commit 9570abd

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

examples/switch.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ const MyItem: React.FC<Item> = ({ id }, ref) => (
1616
lineHeight: '30px',
1717
boxSizing: 'border-box',
1818
display: 'inline-block',
19+
// marginBottom: 8,
1920
}}
2021
>
2122
{id}

src/hooks/useHeights.tsx

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1-
import * as React from 'react';
2-
import { useRef, useEffect } from 'react';
31
import findDOMNode from 'rc-util/lib/Dom/findDOMNode';
42
import raf from 'rc-util/lib/raf';
3+
import * as React from 'react';
4+
import { useEffect, useRef } from 'react';
55
import type { GetKey } from '../interface';
66
import CacheMap from '../utils/CacheMap';
77

8+
function parseNumber(value: string) {
9+
const num = parseFloat(value);
10+
return isNaN(num) ? 0 : num;
11+
}
12+
813
export default function useHeights<T>(
914
getKey: GetKey<T>,
1015
onItemAdd?: (item: T) => void,
@@ -32,8 +37,14 @@ export default function useHeights<T>(
3237
if (element && element.offsetParent) {
3338
const htmlElement = findDOMNode<HTMLElement>(element);
3439
const { offsetHeight } = htmlElement;
35-
if (heightsRef.current.get(key) !== offsetHeight) {
36-
heightsRef.current.set(key, htmlElement.offsetHeight);
40+
const { marginTop, marginBottom } = getComputedStyle(htmlElement);
41+
42+
const marginTopNum = parseNumber(marginTop);
43+
const marginBottomNum = parseNumber(marginBottom);
44+
const totalHeight = offsetHeight + marginTopNum + marginBottomNum;
45+
46+
if (heightsRef.current.get(key) !== totalHeight) {
47+
heightsRef.current.set(key, totalHeight);
3748
}
3849
}
3950
});

0 commit comments

Comments
 (0)