跳到主要内容

useIntersectionObserver

使用 Intersection Observer API 跟踪元素

Usage

实时编辑器
function Demo() {
  const Spacer = () => (
    <div
      style={{
        width: "200px",
        height: "300px",
      }}
    />
  );

  const options = {
    root: null,
    rootMargin: "0px",
    threshold: 1,
  };

  const intersectionRef = useRef(null);
  const [entry, setEntry] = useState<IntersectionObserverEntry[]>([]);
  const stop = useIntersectionObserver(
    intersectionRef,
    (entry) => {
      setEntry(entry);
    },
    options
  );

  return (
    <div
      style={{
        width: "400px",
        height: "400px",
        overflow: "scroll",
      }}
    >
      Scroll me
      <Spacer />
      <button
        onClick={() => {
          stop();
        }}
      >
        stop observe
      </button>
      <div
        ref={intersectionRef}
        style={{
          width: "100px",
          height: "100px",
          padding: "20px",
          background: "var(--c-hj-b)",
        }}
      >
        {entry[0] && entry[0].intersectionRatio < 1
          ? "Obscured"
          : "Fully in view"}
      </div>
      <Spacer />
    </div>
  );
}
结果
Loading...

API

useIntersectionObserver

Returns

() => void: 停止监听函数

Arguments

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