You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

@tanstack/react-table v8:已排序表格中如何获取下一行数据

在TanStack React Table v8中获取排序后行的上下行数据

要拿到排序后行的上下行数据,核心是用表格实例的getRowModel()方法获取已经经过排序/过滤处理后的行数组,然后通过当前行的唯一标识找到它在这个数组里的位置,就能轻松拿到上下行。

具体实现步骤

  1. 在点击事件中,先获取排序后的完整行列表:
    const sortedRows = table.getRowModel().rows;
    这个数组的顺序就是表格最终渲染的顺序,完全匹配排序结果。

  2. 用当前行的id(唯一标识)找到它在排序后数组中的索引:
    const currentIndex = sortedRows.findIndex(r => r.id === row.id);
    用row.id匹配比其他属性更可靠,因为即使排序后,行对象的引用和唯一ID都不会变。

  3. 根据索引获取上下行:

    • 上一行:currentIndex > 0 ? sortedRows[currentIndex - 1] : null
    • 下一行:currentIndex < sortedRows.length - 1 ? sortedRows[currentIndex + 1] : null

完整代码示例

const handleRowClick = (row) => {
  const sortedRows = table.getRowModel().rows;
  const currentIndex = sortedRows.findIndex(r => r.id === row.id);

  const prevRow = currentIndex > 0 ? sortedRows[currentIndex - 1] : null;
  const nextRow = currentIndex < sortedRows.length - 1 ? sortedRows[currentIndex + 1] : null;

  // 可以直接访问行的原始数据
  console.log('上一行数据:', prevRow?.original);
  console.log('下一行数据:', nextRow?.original);
};

补充说明

  • 为什么不用row.index?因为这个属性是原始数据数组中的索引,和排序、过滤后的展示顺序完全无关,所以不能用来定位排序后的位置。
  • 如果你的表格开启了分页,getRowModel().rows只会返回当前页的行,这时候上下行只能在当前页范围内获取;如果需要跨页获取,得结合分页器的pageIndex、pageSize等参数额外处理。

内容的提问来源于stack exchange,提问作者Teckstudio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 03:55:37