useElementSize
追踪 HTML 元素大小的React Hook. ResizeObserver MDN
Usage
实时编辑器
function Demo() { const ref = useRef<HTMLTextAreaElement>(null); const [width, height] = useElementSize(ref, { box: "border-box" }); return ( <div> <div>Resize the box to see changes</div> <br /> <textarea ref={ref} disabled style={{ width: 200, height: 200 }} value={`width: ${width}\nheight: ${height}`} /> </div> ); };
结果
Loading...
API
useElementSize
Returns
readonly [number, number]
: 包含以下元素的元组:
- 元素宽度。
- 元素高度。
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
target | dom对象 | BasicTarget<Element> (必填) | - |
options | resizeObserver 参数 | ResizeObserverOptions | undefined | - |
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;