@ 剪切/ use- get- parent- small -- 从一个缩放的观测器上调整所观察到的 DOM 元素的高度、 宽度等的大小 .
安装
pnpm add @cutting/use-get-parent-size
# or
npm install @cutting/use-get-parent-size
使用亲子关系
一个反应钩子,允许您使用一个缩放观察员来测量元素大小.
使用量
const { width, height } = useParentSize(ref, options);
useParentSize 进行反应 参考对象 和可选 options 对象.
返回所观察到元素的内容矩形 :
interface DOMRectReadOnly {
readonly bottom: number;
readonly height: number;
readonly left: number;
readonly right: number;
readonly top: number;
readonly width: number;
readonly x: number;
readonly y: number;
toJSON(): any;
}
选项
export interface UseParentSizeOptions {
debounceDelay: number;
initialValues: Partial<ResizeObserverContentRect>;
transformFunc?: (entry: Partial<ResizeObserverContentRect>) => Partial<ResizeObserverContentRect>;
maxDifference?: number;
transformFunc?: ({ width, height }: Dimensions) => Dimensions;
callback?(entry: ResizeObserverContentRect): void;
}
debounceDelay- 默认500毫秒可选number它将拖动将事件重新分解到调用码的速度.initialValues- 起初ref将会是null没有width或者说height值可以返回到挂起为止。 这个initialValues选项可以返回特定的width财务报告和审定财务报表height数值直到ref实际引用有效的 DOM 节点。 譬如说.const { width, height } = useParentSize(ref, { width: 100, height: 50})· ;
默认为空 Domrect :
{
bottom: undefined,
height: undefined,
left: undefined,
width: undefined,
right: undefined,
top: undefined,
x: undefined,
y: undefined,
};
-
transformFunc可选函数可转换结果,例如将母体的大小减半transformFunc: ({ width, height }) => ({ width: width / 2, height: height / 2, });默认是身份,
(x) => x -
maxDifference(default 10) - 使用 ParrentSize 将当前 Domrect 值存储在内存中,如果事件发生器的大小调整,这些值会在调整后与新的 Domrect 值相核对. 如果两个值的相差大于maxDifference然后通知客户端. -
callback可以提供每次调整大小时执行的函数.
使用量
用于正确调整 svg 大小
import { useRef } from 'react';
import type { UseParentSizeOptions } from '@cutting/use-get-parent-size';
export function ResponsiveSVG({
children
}): JSX.Element => {
const ref = useRef<HTMLDivElement>(null);
const { width, height } = useParentSize(ref, options);
const aspect = width / height;
const adjustedHeight = Math.ceil(width / aspect);
return (
<div ref={ref}>
<svg
viewBox={`${origin.x} ${origin.y} ${width} ${adjustedHeight}`}
>
{children}
</svg>
</div>
);
};
只使用回调
const Pipeline = () => {
const controller = useVisualizationController();
const containerRef = useRef<HTMLDivElement>(null);
useParentSize(containerRef, {
callback: () => {
controller.getGraph().fit(70);
},
debounceDelay: 500,
});