MUI TablePagination中ActionComponent与Component属性的区别是什么?
MUI TablePagination
Component 与 ActionComponent 属性说明 核心含义澄清
Component:控制整个TablePagination组件渲染的最外层根节点。默认值为td(表格单元格),适配分页放在表格最后一行的常规场景。你可以传入HTML标签字符串(如"div"、"footer"),也可以传入自定义的容器组件,完全替换根节点的类型和样式。ActionComponent:控制分页的操作按钮区域,也就是包含上一页、下一页、页码切换等交互控件的模块。默认使用MUI内置的分页操作组件,你可以传入自定义组件,完全重写分页操作的交互逻辑和视觉样式。
实际使用示例
示例1:自定义Component替换根节点
当你需要把分页放在卡片、弹窗等非表格场景时,不需要默认的<td>根节点,可以直接修改Component属性:
import { useState } from 'react'; import { TablePagination, Card } from '@mui/material'; function CardBottomPagination() { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(10); return ( <Card> {/* 卡片内容区域 */} <div style={{ padding: '16px' }}>列表内容</div> {/* 分页放在卡片底部,根节点用div而非默认td */} <TablePagination Component="div" count={120} page={page} onPageChange={(_, newPage) => setPage(newPage)} rowsPerPage={rowsPerPage} onRowsPerPageChange={(e) => setRowsPerPage(Number(e.target.value))} style={{ justifyContent: 'flex-end' }} /> </Card> ); }
示例2:自定义ActionComponent修改操作区
如果你不需要MUI默认的分页操作样式,想要自定义按钮样式、增加跳转逻辑,可以自定义ActionComponent传入:
import { useState } from 'react'; import { TablePagination, Button } from '@mui/material'; // 自定义分页操作组件,仅保留上一页/下一页按钮 function CustomPaginationAction(props) { const { count, page, rowsPerPage, onPageChange } = props; const totalPage = Math.ceil(count / rowsPerPage); return ( <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}> <Button variant="outlined" size="small" disabled={page === 0} onClick={() => onPageChange(null, page - 1)} > 上一页 </Button> <span>第 {page + 1} 页 / 共 {totalPage} 页</span> <Button variant="outlined" size="small" disabled={page >= totalPage - 1} onClick={() => onPageChange(null, page + 1)} > 下一页 </Button> </div> ); } function CustomActionDemo() { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(10); return ( <TablePagination Component="td" count={120} page={page} onPageChange={(_, newPage) => setPage(newPage)} rowsPerPage={rowsPerPage} onRowsPerPageChange={(e) => setRowsPerPage(Number(e.target.value))} // 传入自定义的操作组件 ActionComponent={CustomPaginationAction} /> ); }
典型使用场景总结
- 调整
Component:分页脱离表格场景使用、需要修改根节点的语义标签、要给最外层容器加自定义的全局样式时使用 - 调整
ActionComponent:需要修改分页操作的交互逻辑、自定义按钮样式、增删操作按钮(如增加首页/尾页按钮、隐藏每页条数选择)时使用
内容的提问来源于stack exchange,提问作者user14853978
相关产品推荐
相关产品推荐

