useResizeObserver
使用 ResizeObserver MDN 跟踪元素大小。
Usage
实时编辑器
function Demo() { const ref = useRef<HTMLTextAreaElement>(null); const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); const stop = useResizeObserver(ref, (entries) => { const [entry] = entries; const { width, height } = entry.contentRect; setWidth(width); setHeight(height); }); 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={`width: ${width}\nheight: ${height}`} /> </div> ); };
结果
Loading...
API
useResizeObserver
Returns
() => void
Arguments
参数名 | 描述 | 类型 | 默认值 |
---|---|---|---|
target | dom元素 | BasicTarget<Element> (必填) | - |
callback | 回调 | ResizeObserverCallback (必填) | - |
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;