Material UI TablePagination自定义文本底部边距问题求解
解决方案
要解决TablePagination单独使用时的垂直居中问题,且符合Material UI设计规范,核心是利用MUI内置的Typography组件渲染分页文本,替代纯文本返回:
使用行内Typography组件
labelDisplayedRows支持返回React节点,我们用Typography并设置component="span"(行内元素),搭配匹配默认样式的文本变体(如body2),既继承MUI设计规范,又不会产生块级元素的多余边距。修改后的完整代码
import { Typography } from '@mui/material'; // 确保导入Typography组件 export default function Pager2(props) { const pagesInResultSet = Math.round(props.resultCount / props.resultsPerPage); const moreThanOnePage = pagesInResultSet > 1; if (!moreThanOnePage) return <>></>; const handleChangePage = (event, newPage) => { props.setCurrentPage(newPage + 1); }; return ( <Container className="pager" align="center"> <TablePagination className="pager-label" align="center" count={props.resultCount} page={props.currentPage - 1} // MUI分页为零基索引 onPageChange={handleChangePage} rowsPerPage={props.resultsPerPage} rowsPerPageOptions={[props.resultsPerPage]} showFirstButton={true} showLastButton={true} labelDisplayedRows={({ from, to, count }) => ( <Typography variant="body2" component="span"> {props.currentPage} of {pagesInResultSet} pages </Typography> )} /> </Container> ); }
- 方案合规性说明
- 复用MUI官方
Typography组件,保证文本样式与MUI设计系统一致; component="span"将元素转为行内类型,消除块级元素默认margin,避免破坏垂直居中布局;- 无需自定义CSS或修改组件根元素(如
component="div"),不会丢失原有组件样式。
内容的提问来源于stack exchange,提问作者DFBerry
相关产品推荐
相关产品推荐

