Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: take margin into account #291

Merged
merged 1 commit into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}

zombieJ marked this conversation as resolved.
Show resolved Hide resolved
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
Loading