自定义分页开发问题:如何将当前页局部卡片完整展示到下一页
解决自定义分页中局部显示卡片的下一页完整渲染问题
问题分析
现有分页逻辑存在三个核心问题:
- 卡片数量计算用
Math.ceil,会把容器剩余空间不足以完整容纳的卡片也算入当前页,导致局部显示 - 仅在组件挂载时计算一次卡片数量,窗口尺寸变化时不会重新计算,无法适配响应式场景
endIdx计算错误,应该是startIdx + cardsPerPage而非currentPage + cardsPerPage
修改方案
- 修正卡片数量计算逻辑:用
Math.floor替代Math.ceil,确保当前页只包含能完整显示的卡片 - 添加窗口 resize 监听:响应式场景下实时更新每页卡片数量
- 修正分页索引计算:修复
endIdx的错误计算逻辑 - 处理边界情况:确保容器过小时至少显示1张卡片,避免异常
修改后的完整代码
import { useEffect, useState, useRef } from 'react'; const YourComponent = () => { const parentRef = useRef(null); const [cardsPerPage, setCardsPerPage] = useState(4); const [currentPage, setCurrentPage] = useState(1); const defaultCardCount = 4; // 实际项目中替换为真实卡片列表的长度 useEffect(() => { const calculateCardsPerPage = () => { const containerWidth = parentRef?.current?.offsetWidth; if (!containerWidth) return; const userCardWidth = 140; const cardWidth = 340; // 计算当前容器能完整容纳的卡片数 const newCardsPerPage = Math.floor( (containerWidth - userCardWidth) / cardWidth ); // 确保至少显示1张卡片 setCardsPerPage(Math.max(newCardsPerPage, 1)); }; // 初始化计算 calculateCardsPerPage(); // 监听窗口尺寸变化 window.addEventListener('resize', calculateCardsPerPage); // 清理监听 return () => window.removeEventListener('resize', calculateCardsPerPage); }, []); // 计算总页数 const totalPages = Math.ceil(defaultCardCount / cardsPerPage); // 修正分页索引 const startIdx = (currentPage - 1) * cardsPerPage; const endIdx = startIdx + cardsPerPage; const handlePaginationClick = (_, page) => { setCurrentPage(page); }; // 组件渲染逻辑 return ( <div ref={parentRef}> {/* 卡片列表:使用startIdx和endIdx截取数据 */} {/* 分页组件 */} </div> ); }; export default YourComponent;
关键说明
Math.floor保证只有能完整放入容器的卡片才会显示在当前页,局部显示的卡片自动归到下一页- 窗口resize监听确保响应式场景下,每次尺寸变化都重新计算每页卡片数
Math.max(newCardsPerPage, 1)避免容器过小时出现每页0张卡片的异常情况- 修正后的
endIdx保证分页截取的索引正确,不会出现越界或错误的卡片范围
内容的提问来源于stack exchange,提问作者dev
相关产品推荐
相关产品推荐

