使用 IntersectionObserver API 用於檢測元素是否在螢幕可見範圍內,並且提供相關的 callback。
JSXimport { useState, useEffect, useRef } from 'react'; export default function useInView(options) { const ref = useRef(); const [isVisible, setIntersectionState] = useState(null); const intersectionCallback = (entries) => { const [entry] = entries; setIntersectionState(entry.isIntersecting); }; useEffect(() => { const observer = new IntersectionObserver(intersectionCallback, { ...options, rootMargin: '0px 0px -100px 0px', }); if (ref.current) observer.observe(ref?.current); return () => { observer.disconnect(); }; }, [ref, options]); return { isVisible, ref }; }
Last Updated:JSXconst App = () => { const { ref, isVisible } = useInView(); return ( <div> // some content <div ref={ref}>{isVisible ? 'The content is visible' : 'The content is not visible'}</div> </div> ); };