41 lines
1.1 KiB
JavaScript
41 lines
1.1 KiB
JavaScript
import { useState, useEffect, useRef, useCallback } from 'react';
|
|
|
|
const useIntersectionObserver = (options = {}) => {
|
|
const [isIntersecting, setIsIntersecting] = useState(false);
|
|
const elementRef = useRef(null);
|
|
const observerRef = useRef(null);
|
|
|
|
useEffect(() => {
|
|
// 如果已有观察器,先断开
|
|
if (observerRef.current) {
|
|
observerRef.current.disconnect();
|
|
}
|
|
|
|
const observerOptions = {
|
|
threshold: options.threshold || 0.1,
|
|
rootMargin: options.rootMargin || '0px',
|
|
root: options.root || null
|
|
};
|
|
|
|
observerRef.current = new IntersectionObserver(([entry]) => {
|
|
// 避免在组件卸载后设置状态
|
|
if (elementRef.current) {
|
|
setIsIntersecting(entry.isIntersecting);
|
|
}
|
|
}, observerOptions);
|
|
|
|
if (elementRef.current) {
|
|
observerRef.current.observe(elementRef.current);
|
|
}
|
|
|
|
return () => {
|
|
if (observerRef.current) {
|
|
observerRef.current.disconnect();
|
|
}
|
|
};
|
|
}, [options.threshold, options.rootMargin, options.root]);
|
|
|
|
return [elementRef, isIntersecting];
|
|
};
|
|
|
|
export default useIntersectionObserver; |