文章预览
在现代 Web 应用中, 检测元素是否进入视口 是一个常见需求,尤其是在实现懒加载、无限滚动或跟踪广告曝光等场景中。 useIntersectionObserver 钩子提供了一种声明式的方法来利用 Intersection Observer API,使得监测元素可见性变得简单而高效。这个自定义钩子不仅简化了 Intersection Observer 的使用,还使其完全适配 React 的组件生命周期。以下是如何实现和使用这个自定义钩子: const useIntersectionObserver = ( ref, options ) => { const [isIntersecting, setIsIntersecting] = React.useState( false ); React.useEffect( () => { const observer = new IntersectionObserver( ( [entry] ) => { setIsIntersecting(entry.isIntersecting); }, options); if (ref.current) { observer.observe(ref.current); } return () => { observer.unobserve(ref.current); }; },
………………………………