MUI TablePagination中如何将displayRows段落放在上下页按钮之间
自定义TablePagination分页按钮排布实现
直接通过TablePagination提供的ActionsComponent属性自定义分页操作区结构,即可将当前行数据范围提示放在上一页、下一页按钮中间,不需要修改组件内部源码。
实现步骤
- 先编写自定义的分页操作组件,按照「上一页按钮 -> 行范围文本 -> 下一页按钮」的顺序排布:
import { IconButton } from '@mui/material'; import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft'; import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight'; const CustomPaginationActions = (props) => { const { count, page, rowsPerPage, onPageChange, labelDisplayedRows } = props; const handlePrev = (e) => onPageChange(e, page - 1); const handleNext = (e) => onPageChange(e, page + 1); const isLastPage = page >= Math.ceil(count / rowsPerPage) - 1; return ( <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> <IconButton onClick={handlePrev} disabled={page === 0} aria-label="上一页"> <KeyboardArrowLeft /> </IconButton> {/* 行范围提示放在两个按钮中间 */} <span style={{ margin: 0, fontSize: 14 }}> {labelDisplayedRows({ from: count === 0 ? 0 : page * rowsPerPage + 1, to: Math.min(count, (page + 1) * rowsPerPage), count, page })} </span> <IconButton onClick={handleNext} disabled={isLastPage} aria-label="下一页"> <KeyboardArrowRight /> </IconButton> </div> ); };
- 将自定义组件传入原TablePagination的
ActionsComponent属性即可:
<TablePagination rowsPerPageOptions={[]} component="div" count={rows} page={page} onPageChange={handleChangePage} rowsPerPage={rowsPerPage} onRowsPerPageChange={handleChangeRowsPerPage} ActionsComponent={CustomPaginationActions} />
注意事项
- 保留
rowsPerPageOptions={[]}配置即可自动隐藏每页行数选择下拉框 - 可以自行调整容器间距、文本字号样式适配项目设计规范
- TypeScript项目可直接给自定义操作组件引入
TablePaginationActionsProps作为props类型,不需要额外写类型定义
内容的提问来源于stack exchange,提问作者Znatok
相关产品推荐
相关产品推荐

