交叉观察器IntersectionObserver对象实战使用
用IntersectionObserver判断滚动页面是否到达底部
import { Toast } from "antd-mobile";
import { useRef, useLayoutEffect, useMemo } from "react";
import { v4 as uuid } from "uuid";
const MyPage = () => {
const bottomRef = useRef<HTMLDivElement | null>(null);
const list = useMemo(() => {
return new Array(200)
.fill(0)
.map(() => ({ key: uuid().replace(/-/g, "").substring(0, 18) }));
}, []);
useLayoutEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
console.log("到底了");
Toast.show({
position: "center",
content: "到底了",
});
}
},
{
root: document.getElementById("myComponent"),
rootMargin: "0px",
threshold: 1.0,
}
);
if (bottomRef.current) {
observer.observe(bottomRef.current);
}
return () => {
if (bottomRef.current) {
observer.unobserve(bottomRef.current);
}
};
}, []);
return (
<div
id="myComponent"
style={{
height: "calc(100vh - 48px)",
overflowY: "auto",
padding: "24px",
}}
>
{Array.isArray(list) &&
list.map((item, index) => {
return <div key={item.key}>{`${index} --> ${item?.key}`}</div>;
})}
<div ref={bottomRef} style={{ height: "1px" }} />
</div>
);
};
export default MyPage;