useFillHeight.ts
1.11 KB
import { useLayoutEffect, useRef, useState } from 'react';
/**
* 测量填充表格可滚动表体的高度。
* 监听外层容器尺寸,扣除表头与分页高度后返回 scroll.y,
* 与 antd 内部 DOM 结构解耦,版本无关。
*/
export function useFillHeight() {
const wrapRef = useRef<HTMLDivElement>(null);
const [bodyHeight, setBodyHeight] = useState<number | undefined>(undefined);
useLayoutEffect(() => {
const wrap = wrapRef.current;
if (!wrap) return;
const measure = () => {
const header = wrap.querySelector('.ant-table-thead');
const pagination = wrap.querySelector('.ant-table-pagination');
const headerH = header ? (header as HTMLElement).getBoundingClientRect().height : 0;
const pagH = pagination ? (pagination as HTMLElement).offsetHeight : 0;
const available = Math.max(0, wrap.clientHeight - headerH - pagH);
setBodyHeight((prev) => (prev === available ? prev : available));
};
const ro = new ResizeObserver(measure);
ro.observe(wrap);
measure();
return () => ro.disconnect();
}, []);
return { wrapRef, bodyHeight };
}