跳到主要内容

useElementBounding

追踪 HTML 元素边界框的 React Hook

Usage

实时编辑器

function Demo() {
  const ref = useRef<HTMLTextAreaElement>(null);
  const rect = useElementBounding(ref);
  return (
    <div>
      <p> Resize the box to see changes</p>
      <textarea ref={ref} readOnly value={JSON.stringify(rect, null, 2)} />
    </div>
  );
};

结果
Loading...

API

useElementBounding

Returns

UseElementBoundingReturn

Arguments

参数名描述类型默认值
target目标元素BasicTarget<Element> (必填)-
options可选参数UseElementBoundingOptions | undefined-

UseElementBoundingOptions

参数名描述类型默认值
reset将数值重置为0booleantrue
windowResize是否监听 resize 事件booleantrue
windowScroll是否监听 scroll 事件booleantrue
immediate立即更新boolean-

UseElementBoundingReturn

参数名描述类型默认值
height元素的高度number (必填)-
bottom元素的底部位置number (必填)-
left元素的左侧位置number (必填)-
right元素的右侧位置number (必填)-
top元素的顶部位置number (必填)-
width元素的宽度number (必填)-
x元素的 X 位置number (必填)-
y元素的 Y 位置number (必填)-
update手动更新() => void (必填)-

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;