Files
teach_sys_Demo/src/components/InfiniteScroll/index.jsx

55 lines
1.3 KiB
React
Raw Normal View History

import { useEffect, useRef, useState } from "react";
import { Empty } from "@arco-design/web-react";
const InfiniteScroll = ({
loadMore,
hasMore,
children,
threshold = 50,
className = "",
}) => {
const containerRef = useRef(null);
2025-08-20 18:05:50 +08:00
const [loading, setLoading] = useState(false);
2025-08-20 18:05:50 +08:00
const handleScroll = () => {
if (loading) return;
setLoading(true);
if (!containerRef.current || !hasMore) return;
2025-08-20 18:05:50 +08:00
const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
2025-08-20 18:05:50 +08:00
if (scrollTop + clientHeight >= scrollHeight - threshold) {
loadMore().finally(() => {
setLoading(false);
});
}
};
2025-08-20 18:05:50 +08:00
useEffect(() => {
const container = containerRef.current;
if (container) {
container.addEventListener("scroll", handleScroll);
// 初始加载时检查是否需要加载更多
handleScroll();
}
return () => {
if (container) {
container.removeEventListener("scroll", handleScroll);
}
};
}, [loadMore, hasMore, threshold]);
return (
<div
ref={containerRef}
className={`infinite-scroll-container ${className}`}
>
{children}
{!hasMore && !loading && <Empty description="没有更多了" />}
</div>
);
};
export default InfiniteScroll;