Skip to content

Commit

Permalink
fix: take margin into account (#291)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ authored Nov 5, 2024
1 parent 8ff44e2 commit 9570abd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
1 change: 1 addition & 0 deletions examples/switch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const MyItem: React.FC<Item> = ({ id }, ref) => (
lineHeight: '30px',
boxSizing: 'border-box',
display: 'inline-block',
// marginBottom: 8,
}}
>
{id}
Expand Down
19 changes: 15 additions & 4 deletions src/hooks/useHeights.tsx
Original file line number Diff line number Diff line change
@@ -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<T>(
getKey: GetKey<T>,
onItemAdd?: (item: T) => void,
Expand Down Expand Up @@ -32,8 +37,14 @@ export default function useHeights<T>(
if (element && element.offsetParent) {
const htmlElement = findDOMNode<HTMLElement>(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);
}
}
});
Expand Down

0 comments on commit 9570abd

Please sign in to comment.