跳到主要内容

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

参数名描述类型默认值
targetdom元素BasicTarget<Element> (必填)-
callback回调ResizeObserverCallback (必填)-
optionsresizeObserver 参数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;