跳到主要内容

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

参数名描述类型默认值
targetdom对象BasicTarget<Element> (必填)-
options可选参数ResizeObserverOptions | undefined-

UseMeasureRect

参数名描述类型默认值
topMDN Referencenumber (必填)-
bottomMDN Referencenumber (必填)-
leftMDN Referencenumber (必填)-
rightMDN Referencenumber (必填)-
heightMDN Referencenumber (必填)-
widthMDN Referencenumber (必填)-
xMDN Referencenumber (必填)-
yMDN Referencenumber (必填)-

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;