useMeasure
使用 Resize Observer API
跟踪 HTML 元素的尺寸
Usage
实时编辑器
function Demo() { const ref = useRef<HTMLTextAreaElement>(null); const [rect, stop] = useMeasure(ref); return ( <div> <div>Resize the box to see changes</div> <div> <button onClick={() => stop()}>stop observe</button> </div> <br /> <textarea ref={ref} disabled style={{ width: 286, height: 166 }} value={JSON.stringify(rect, null, 2)} /> </div> ); };
结果
Loading...
API
useMeasure
Returns
readonly [UseMeasureRect, () => void]
: [DOMRect值,停止监听函数]
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
target | dom对象 | BasicTarget<Element> (必填) | - |
options | 可选参数 | ResizeObserverOptions | undefined | - |
UseMeasureRect
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
top | MDN Reference | number (必填) | - |
bottom | MDN Reference | number (必填) | - |
left | MDN Reference | number (必填) | - |
right | MDN Reference | number (必填) | - |
height | MDN Reference | number (必填) | - |
width | MDN Reference | number (必填) | - |
x | MDN Reference | number (必填) | - |
y | MDN Reference | number (必填) | - |
BasicTarget
export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;
TargetValue
type TargetValue<T> = T | undefined | null;
TargetType
type TargetType = HTMLElement | Element | Window | Document | EventTarget;