useElementVisibility
追踪视窗内元素可见性的 React Hook。这是 useIntersectionObserver 的一个封装器
useElementVisibility 提供一个简单的布尔值,表示 DOM 元素当前是否在视口内可见。它基于 useIntersectionObserver 构建,抽象了 Intersection Observer API 的复杂性。它返回一个 [isVisible, stop] 元组,其中 stop 是断开观察器的函数。
使用场景
- 当元素滚动到视图中时触发动画或懒加载内容
- 为信息流项目或通知实现”已读回执”或”已看”跟踪
- 在元素不在屏幕上时有条件地渲染或暂停资源密集型组件
注意事项
- SSR 安全:在服务端渲染期间返回
false,因为没有可用的 DOM。 - 可自定义:接受标准的
IntersectionObserverInit选项(root、rootMargin、threshold),精细控制可见性触发时机。 - 参见
useIntersectionObserver了解完整访问IntersectionObserverEntry数据,以及useDocumentVisibility了解页面级(标签页)可见性。
Usage
Live Editor
function Demo() { const ref = useRef<HTMLDivElement>(null); const [visible, stop] = useElementVisibility(ref); return ( <div> <p>右下角的信息</p> <div ref={ref} style={{ borderWidth: 2, borderStyle: "solid", padding: "1rem", }} > 目标元素(向下滚动) </div> <button onClick={() => { stop(); }} > 停止 </button> <div style={{ borderWidth: 2, borderStyle: "solid", padding: "1rem", position: "fixed", bottom: 0, right: 0, zIndex: 100, }} > 元素 {visible ? "在视窗内" : "在视窗外"} </div> </div> ); };
Result
API
useElementVisibility
Returns
readonly [boolean, () => void]: 包含以下元素的元组:
- 当前元素是否可见。
- 停止监听函数。
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| target | dom对象 | 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;