我本來想要講解IntersectionObserver這個api的,但是我覺得莫力全前輩之前寫的文章更好,所以決定直接放他的文章連結,他講解得非常清楚,如果不知道這個是什麼web api,歡迎去看,關於IntersectionObserver他寫在文章的中後段
文章url:
https://ithelp.ithome.com.tw/articles/10272251?sc=rss.iron
import { RefObject, useEffect, useState, useRef } from "react";
function useIntersectionObserver(
target: RefObject<Element>,
options: IntersectionObserverInit = {}
): boolean {
const [isIntersecting, setIntersecting] = useState<boolean>(false);
const observer = useRef<IntersectionObserver>(
new IntersectionObserver(
([entry]) => setIntersecting(entry.isIntersecting),
options
)
);
useEffect(() => {
const currentObserver = observer.current;
const currentTarget = target.current;
if (currentTarget) {
currentObserver.observe(currentTarget);
}
return () => {
if (currentTarget) {
currentObserver.unobserve(currentTarget);
}
};
}, [target]);
return isIntersecting;
}
export default useIntersectionObserver;
接下來就能使用了,用一個簡單的範例來寫,實際上可能會更複雜,例如你可能會需要換頁,再call api加資料等,像FB那樣infinite scroll,這邊就做一個簡單版的
import React, { useRef } from 'react';
import useIntersectionObserver from './useIntersectionObserver';
const TestComponent: React.FC = () => {
const ref = useRef<HTMLDivElement>(null);
const isIntersecting = useIntersectionObserver(ref, {
rootMargin: '0px',
threshold: 0.5,
});
return (
<div ref={ref} style={{ height: '200px', width: '200px' }}>
{isIntersecting ? 'InView' : 'OutView'}
</div>
);
};
export default TestComponent;
這樣就看起來是沒問題的