求助:如何在React Table中实现指定格式的分页页码显示
实现 React Table 自定义分页逻辑
核心思路
根据你提供的分页格式,我们需要动态生成页码元素,规则如下:
- 始终显示第一页和最后一页
- 当前页前后各显示2个相邻页码(前几页和后几页的特殊情况除外)
- 非连续的页码区间用
...占位 - 显示上一页(
<)和下一页(>)按钮 - 当前页用
[]包裹(可通过样式强化区分)
实现步骤
1. 编写页码生成函数
根据 React Table 提供的 pageIndex(从0开始)和 pageCount,生成符合要求的页码列表:
const generatePaginationItems = (currentPageIndex, totalPages) => { const items = []; // 转换为从1开始的当前页码 const currentPage = currentPageIndex + 1; // 添加上一页按钮 items.push({ type: 'prev', targetIndex: currentPageIndex - 1 }); // 始终添加第一页 items.push({ type: 'page', number: 1, isCurrent: currentPage === 1 }); // 处理第一页后的省略号 if (currentPage > 4) { items.push({ type: 'ellipsis' }); } // 添加当前页前后的相邻页码 const startRange = Math.max(2, currentPage - 2); const endRange = Math.min(totalPages - 1, currentPage + 2); for (let i = startRange; i <= endRange; i++) { items.push({ type: 'page', number: i, isCurrent: currentPage === i }); } // 处理最后一页前的省略号 if (currentPage < totalPages - 3) { items.push({ type: 'ellipsis' }); } // 始终添加最后一页(总页数大于1时) if (totalPages > 1) { items.push({ type: 'page', number: totalPages, isCurrent: currentPage === totalPages }); } // 添加下一页按钮 items.push({ type: 'next', targetIndex: currentPageIndex + 1 }); return items; };
2. 组件中渲染分页元素
结合 React Table 实例数据,调用函数并渲染分页组件:
const { pageIndex, pageCount, gotoPage } = tableInstance; const paginationItems = generatePaginationItems(pageIndex, pageCount); return ( <div className="pagination-container"> {paginationItems.map((item, idx) => { if (item.type === 'page') { return ( <button key={idx} onClick={() => gotoPage(item.number - 1)} // 转换回0开始的pageIndex className={item.isCurrent ? 'current-page-btn' : 'page-btn'} > {item.isCurrent ? `[${item.number}]` : item.number} </button> ); } else if (item.type === 'ellipsis') { return <span key={idx} className="ellipsis">...</span>; } else if (item.type === 'prev' || item.type === 'next') { const isDisabled = item.type === 'prev' ? pageIndex === 0 : pageIndex === pageCount - 1; return ( <button key={idx} onClick={() => !isDisabled && gotoPage(item.targetIndex)} disabled={isDisabled} className="nav-btn" > {item.type === 'prev' ? '<' : '>'} </button> ); } return null; })} </div> );
3. 基础样式补充
通过CSS优化分页元素的显示效果:
.pagination-container { display: flex; gap: 10px; align-items: center; padding: 10px; } .page-btn, .nav-btn { padding: 6px 10px; border: 1px solid #e0e0e0; background-color: #fff; cursor: pointer; border-radius: 4px; } .current-page-btn { padding: 6px 10px; border: 1px solid #2196f3; background-color: #2196f3; color: #fff; font-weight: bold; border-radius: 4px; } .nav-btn:disabled { opacity: 0.5; cursor: not-allowed; } .ellipsis { color: #666; }
边界情况说明
- 当总页数少于5时,不会显示省略号,直接展示所有页码
- 上一页/下一页按钮在首尾页会自动禁用,避免无效操作
- 处理了当前页为前4页或后4页时的特殊显示逻辑,保证页码连续性
内容的提问来源于stack exchange,提问作者Aniket Deshpande
相关产品推荐
相关产品推荐

