跳到主要内容

useElementVisibility

追踪视窗内元素可见性的 React Hook。这是 useIntersectionObserver 的一个封装器

Usage

实时编辑器

function Demo() {
  const ref = useRef<HTMLDivElement>(null);
  const [visible, stop] = useElementVisibility(ref);

  return (
    <div>
      <p>Info on the right bottom corner</p>
      <div
        ref={ref}
        style={{
          borderWidth: 2,
          borderStyle: "solid",
          padding: "1rem",
        }}
      >
        Target Element (scroll down)
      </div>
      <button
        onClick={() => {
          stop();
        }}
      >
        Stop
      </button>
      <div
        style={{
          borderWidth: 2,
          borderStyle: "solid",
          padding: "1rem",
          position: "fixed",
          bottom: 0,
          right: 0,
          zIndex: 100,
        }}
      >
        Element {visible ? "inside" : "outside"} the viewport
      </div>
    </div>
  );
};

结果
Loading...

API

useElementVisibility

Returns

readonly [boolean, () => void]: 包含以下元素的元组:

  • 当前元素是否可见。
  • 停止监听函数。

Arguments

参数名描述类型默认值
targetdom对象BasicTarget<HTMLElement | SVGElement> (必填)-
options传递给 intersectionObserver 的选项IntersectionObserverInit | 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;