跳到主要内容

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

参数名描述类型默认值
targetdom对象BasicTarget<Element> (必填)-
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;