
本文详解如何使用 react-infinite-scroll-component 在 react/typescript 项目中实现响应式无限滚动,支持首次加载 10 条动态、触底自动加载下一批 10 条,并兼顾移动端和桌面端滚动容器兼容性。
在现代社交类或内容聚合型应用中,无限滚动(Infinite Scroll)是提升用户体验的关键交互模式。相比传统分页,它能减少用户操作、避免页面跳转,并自然适配移动端浏览习惯。本文将基于你已有的 MainSection 组件,完整集成 react-infinite-scroll-component,实现首次渲染 10 条帖子 → 滚动至末尾时加载下 10 条 → 支持桌面端(窗口滚动)与移动端(容器内滚动)双模式。
✅ 前置准备:安装依赖
npm install react-infinite-scroll-component # 或 yarn add react-infinite-scroll-component
✅ 步骤一:改造状态管理与数据切片逻辑
首先,在 MainSection 中引入必要 Hook 和状态,并分离「原始数据」与「当前展示数据」:
import { useState, useEffect, useRef } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import PostStyles from '../../../components/ui/createPost/_createpost.module.scss';
import CreatePost from '../createPost/createPost';
import Post from '../post/post';
import Modal from '../createPost/Modal';
import { postType } from '../../../util/types';
type mainSectionType = {
posts: postType[]; // 原始全量数据(可来自 props 或服务端分页 API)
};
const MainSection = ({ posts }: mainSectionType) => {
const [slicedData, setSlicedData] = useState([]);
const [hasMore, setHasMore] = useState(true);
const [startIndex, setStartIndex] = useState(0);
const itemsPerPage = 10;
const scrollableDivRef = useRef(null);
// 初始加载第一页(前 10 条)
useEffect(() => {
setSlicedData(posts.slice(0, itemsPerPage));
setHasMore(posts.length > itemsPerPage);
setStartIndex(itemsPerPage);
}, [posts]);
// 加载下一批数据
const loadMorePosts = () => {
if (startIndex >= posts.length) return;
const nextBatch = posts.slice(startIndex, startIndex + itemsPerPage);
setSlicedData(prev => [...prev, ...nextBatch]);
const newStartIndex = startIndex + itemsPerPage;
setStartIndex(newStartIndex);
setHasMore(newStartIndex < posts.length);
};
return (
<>
{/* 关键:为无限滚动提供明确的滚动容器 */}
}
endMessage={
? You've reached the end!
}
// ✅ 移动端 & 桌面端兼容关键配置:
scrollableTarget="scrollableDiv" // 指定容器 ID(必须唯一且存在)
// 如果希望监听 window 滚动(如整个页面滚动),则移除 scrollableTarget 并确保父容器不设 overflow
>
{slicedData.map((post, index) => (
))}










