Material-Table自定义分页保留默认功能仅改样式
Material-Table 自定义分页保留全量功能实现
问题原因
当前自定义分页组件仅提取了相邻页切换相关的props,没有接入每页行数修改、首尾页跳转对应的回调与配置,导致功能缺失。实际上Material-Table会向自定义Pagination组件传入所有原生分页所需的参数,不需要重写分页逻辑,只需要补全对应交互元素、绑定传入的回调即可,完全可以在自定义样式的同时保留所有默认功能。
完整实现代码
首先提前导入需要用到的Material UI依赖:
import { Grid, IconButton, Typography, Select, MenuItem } from '@material-ui/core'; import { SkipPrevious, SkipNext, FirstPage, LastPage } from '@material-ui/icons';
修改列表组件代码如下:
function IntakeList() { const CustomPaginationComponent = (props) => { const { page, rowsPerPage, count, onChangePage, onChangeRowsPerPage, rowsPerPageOptions } = props; // 计算当前页展示条目区间 const from = rowsPerPage * page + 1; let to = rowsPerPage * (page + 1); to = to > count ? count : to; // 计算总页数 const totalPages = Math.ceil(count / rowsPerPage); return ( <td> <Grid container alignItems="center" spacing={2} style={{ padding: '8px 16px' }}> {/* 首页跳转按钮 */} <Grid item> <IconButton disabled={page === 0} onClick={(e) => onChangePage(e, 0)} > <FirstPage fontSize="small" color={page === 0 ? "disabled" : "primary"} /> </IconButton> </Grid> {/* 上一页按钮 */} <Grid item> <IconButton disabled={page === 0} onClick={(e) => onChangePage(e, page - 1)} > <SkipPrevious fontSize="small" color={page === 0 ? "disabled" : "primary"} /> <Typography>Prev</Typography> </IconButton> </Grid> {/* 条目计数展示 */} <Grid item> <Typography variant="caption" style={{ color: "black" }}> {from}-{to} of {count} </Typography> </Grid> {/* 下一页按钮 */} <Grid item> <IconButton disabled={to >= count} onClick={(e) => onChangePage(e, page + 1)} > <Typography>Next</Typography> <SkipNext fontSize="small" color={to < count ? "primary" : "disabled"} /> </IconButton> </Grid> {/* 尾页跳转按钮 */} <Grid item> <IconButton disabled={page >= totalPages - 1} onClick={(e) => onChangePage(e, totalPages - 1)} > <LastPage fontSize="small" color={page >= totalPages -1 ? "disabled" : "primary"} /> </IconButton> </Grid> {/* 每页行数选择器 */} <Grid item> <Grid container alignItems="center" spacing={1}> <Grid item> <Typography variant="caption">Rows per page:</Typography> </Grid> <Grid item> <Select value={rowsPerPage} onChange={onChangeRowsPerPage} variant="standard" disableUnderline > {rowsPerPageOptions.map(option => ( <MenuItem key={option} value={option}> {option} </MenuItem> ))} </Select> </Grid> </Grid> </Grid> </Grid> </td> ); }; return ( <MaterialTable title="Title" data={data} columns={columns} options={{ pageSize: 10, pageSizeOptions: [10, 15, 25, 50, 100], }} components={{ Pagination: (props) => <CustomPaginationComponent {...props} />, }} /> ); }
调整说明
- 所有交互逻辑均调用Material-Table传入的原生回调,不会破坏默认分页行为
- 可直接修改Grid间距、内边距、文本样式、图标配色等属性,按需调整视觉效果
- 如果需要新增页码直接跳转功能,只需新增输入组件,输入合法页码后调用
onChangePage(e, 目标页码-1)即可
内容的提问来源于stack exchange,提问作者Ciaran Crowley
相关产品推荐
相关产品推荐

