feat: 🎸 封装了一个滚动加载组件
This commit is contained in:
20
src/components/InfiniteScroll/index.css
Normal file
20
src/components/InfiniteScroll/index.css
Normal file
@@ -0,0 +1,20 @@
|
||||
.infinite-scroll-container {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.loading-indicator {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 16px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.no-more-data {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 16px;
|
||||
color: #999;
|
||||
}
|
||||
57
src/components/InfiniteScroll/index.jsx
Normal file
57
src/components/InfiniteScroll/index.jsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Empty } from "@arco-design/web-react";
|
||||
import { useSelector } from "react-redux";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { setLoadingTrue, setLoadingFalse } from "@/store/slices/loadingSlice";
|
||||
|
||||
const InfiniteScroll = ({
|
||||
loadMore,
|
||||
hasMore,
|
||||
children,
|
||||
threshold = 50,
|
||||
className = "",
|
||||
}) => {
|
||||
const dispatch = useDispatch();
|
||||
const containerRef = useRef(null);
|
||||
const loading = useSelector((state) => state.loading.value);
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
if (!containerRef.current || loading || !hasMore) return;
|
||||
|
||||
const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
|
||||
|
||||
if (scrollTop + clientHeight >= scrollHeight - threshold) {
|
||||
dispatch(setLoadingTrue());
|
||||
loadMore().finally(() => {
|
||||
dispatch(setLoadingFalse());
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const container = containerRef.current;
|
||||
if (container) {
|
||||
container.addEventListener("scroll", handleScroll);
|
||||
// 初始加载时检查是否需要加载更多
|
||||
handleScroll();
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (container) {
|
||||
container.removeEventListener("scroll", handleScroll);
|
||||
}
|
||||
};
|
||||
}, [loadMore, hasMore, threshold, loading]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={`infinite-scroll-container ${className}`}
|
||||
>
|
||||
{children}
|
||||
{!hasMore && !loading && <Empty description="没有更多了" />}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default InfiniteScroll;
|
||||
@@ -11,7 +11,7 @@ const Layout = ({ children }) => {
|
||||
return (
|
||||
<div className="app-layout">
|
||||
<Sidebar isCollapsed={isCollapsed} setIsCollapsed={setIsCollapsed} />
|
||||
<Spin loading={loading} size={40} className="app-layout-spin">
|
||||
<Spin block loading={loading} size={40} className="app-layout-spin">
|
||||
<main className="main-content">{children}</main>
|
||||
</Spin>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user