使用MUI DataGrid (Pro)客户端排序时,如何获取行的当前顺序?
在MUI DataGrid客户端模式下获取排序后的行顺序
当然可以,在客户端排序模式下,你完全可以借助DataGrid的内置API直接获取当前排序后的行顺序,不用自己重复实现排序逻辑。
核心实现方式
通过useGridApiRef获取表格的API引用,调用内置方法就能拿到排序后的行信息:
apiRef.current.getSortedRowIds():返回当前表格展示顺序的行ID数组- 用这个ID数组映射你的原始行数据,就能得到完整的排序后行列表
代码示例
import { DataGrid, useGridApiRef } from '@mui/x-data-grid'; function YourGrid() { const apiRef = useGridApiRef(); const rows = [...]; // 你的原始行数据 const columns = [...]; // 列配置 // 获取当前排序后的完整行数据 const getSortedRows = () => { const sortedIds = apiRef.current.getSortedRowIds(); return sortedIds.map(id => rows.find(row => row.id === id)); }; // 处理行点击,记录当前行在排序列表中的位置 const handleRowClick = (params) => { const sortedRows = getSortedRows(); const currentIndex = sortedRows.findIndex(row => row.id === params.id); // 把currentIndex和排序后的ID列表存入状态或路由参数,供详情页切换使用 console.log('当前行在排序列表中的索引:', currentIndex); }; return ( <DataGrid apiRef={apiRef} rows={rows} columns={columns} sortingMode="client" // 确保开启客户端排序 onRowClick={handleRowClick} /> ); }
适配你的详情页切换场景
- 跳转详情页时,把当前行ID和排序后的行ID列表(或当前索引)一起传递过去
- 在详情页中,根据ID列表找到当前行的索引,点击「上一页」「下一页」时直接取对应索引的行ID,跳转至对应详情页即可
注意事项
- 该方法仅在
sortingMode="client"下有效,因为客户端模式下DataGrid会自行维护排序后的行状态 - 如果行数据是动态更新的,调用
getSortedRows时要确保使用最新的原始行数据
内容的提问来源于stack exchange,提问作者Eric Liprandi
相关产品推荐
相关产品推荐

