2025-08-20 16:29:11 +08:00
|
|
|
import { useEffect, useRef, useState } from "react";
|
2025-08-21 00:10:13 +08:00
|
|
|
import { Empty, Spin } from "@arco-design/web-react";
|
|
|
|
|
import "./index.css";
|
2025-08-20 16:29:11 +08:00
|
|
|
|
|
|
|
|
const InfiniteScroll = ({
|
|
|
|
|
loadMore,
|
|
|
|
|
hasMore,
|
|
|
|
|
children,
|
|
|
|
|
threshold = 50,
|
|
|
|
|
className = "",
|
2025-08-21 00:10:13 +08:00
|
|
|
empty = false,
|
2025-08-20 16:29:11 +08:00
|
|
|
}) => {
|
|
|
|
|
const containerRef = useRef(null);
|
2025-08-20 18:05:50 +08:00
|
|
|
const [loading, setLoading] = useState(false);
|
2025-08-20 16:29:11 +08:00
|
|
|
|
2025-08-20 18:05:50 +08:00
|
|
|
const handleScroll = () => {
|
|
|
|
|
if (loading) return;
|
|
|
|
|
setLoading(true);
|
2025-08-20 22:39:05 +08:00
|
|
|
if (!containerRef.current || !hasMore) return;
|
2025-08-20 16:29:11 +08:00
|
|
|
|
2025-08-20 18:05:50 +08:00
|
|
|
const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
|
2025-08-20 16:29:11 +08:00
|
|
|
|
2025-08-20 18:05:50 +08:00
|
|
|
if (scrollTop + clientHeight >= scrollHeight - threshold) {
|
|
|
|
|
loadMore().finally(() => {
|
|
|
|
|
setLoading(false);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
};
|
2025-08-20 16:29:11 +08:00
|
|
|
|
2025-08-20 18:05:50 +08:00
|
|
|
useEffect(() => {
|
2025-08-20 16:29:11 +08:00
|
|
|
const container = containerRef.current;
|
|
|
|
|
if (container) {
|
|
|
|
|
container.addEventListener("scroll", handleScroll);
|
|
|
|
|
// 初始加载时检查是否需要加载更多
|
|
|
|
|
handleScroll();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
if (container) {
|
|
|
|
|
container.removeEventListener("scroll", handleScroll);
|
|
|
|
|
}
|
|
|
|
|
};
|
2025-08-20 22:39:05 +08:00
|
|
|
}, [loadMore, hasMore, threshold]);
|
2025-08-20 16:29:11 +08:00
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<div
|
|
|
|
|
ref={containerRef}
|
|
|
|
|
className={`infinite-scroll-container ${className}`}
|
|
|
|
|
>
|
|
|
|
|
{children}
|
2025-08-21 00:10:13 +08:00
|
|
|
|
|
|
|
|
{!hasMore && empty && (
|
|
|
|
|
<Empty description="暂无数据" className="empty-data" />
|
|
|
|
|
)}
|
|
|
|
|
{/* 滚动加载指示器 */}
|
|
|
|
|
{loading && hasMore && (
|
|
|
|
|
<div className="loading-container">
|
|
|
|
|
<Spin size="small" />
|
|
|
|
|
<span className="loading-text">加载中...</span>
|
|
|
|
|
</div>
|
|
|
|
|
)}
|
2025-08-20 16:29:11 +08:00
|
|
|
</div>
|
|
|
|
|
);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default InfiniteScroll;
|