框架
版本
企业版

行指南

API

行 API

行指南

本快速指南将讨论在 TanStack Table 中检索和操作行对象的不同方法。

从何处获取行

您可以使用多个 table 实例 API 从表实例中检索行。

table.getRow

如果您需要通过其 id 访问特定行,您可以使用 table.getRow 表实例 API。

js
const row = table.getRow(rowId)
const row = table.getRow(rowId)

行模型

table 实例会生成 row 对象,并将它们存储在称为 “行模型” 的有用数组中。这将在 行模型指南 中更详细地讨论,但以下是您可能访问行模型的最常见方式。

渲染行
jsx
<tbody>
  {table.getRowModel().rows.map(row => (
    <tr key={row.id}>
     {/* ... */}
    </tr>
  ))}
</tbody>
<tbody>
  {table.getRowModel().rows.map(row => (
    <tr key={row.id}>
     {/* ... */}
    </tr>
  ))}
</tbody>
获取选中的行
js
const selectedRows = table.getSelectedRowModel().rows
const selectedRows = table.getSelectedRowModel().rows

行对象

每个行对象都包含行数据和许多 API,可用于与表状态进行交互或根据表状态从行中提取单元格。

行 ID

每个行对象都有一个 id 属性,使其在表实例中具有唯一性。默认情况下,row.id 与行模型中创建的 row.index 相同。但是,使用行数据中的唯一标识符来覆盖每个行的 id 可能很有用。您可以使用 getRowId 表选项来实现此目的。

js
const table = useReactTable({
  columns,
  data,
  getRowId: originalRow => originalRow.uuid, //override the row.id with the uuid from the original row's data
})
const table = useReactTable({
  columns,
  data,
  getRowId: originalRow => originalRow.uuid, //override the row.id with the uuid from the original row's data
})

注意:在分组和展开等某些功能中,row.id 将会附加额外的字符串。

访问行值

从行访问数据值的推荐方法是使用 row.getValuerow.renderValue API。使用任一 API 都将缓存访问器函数的结果并保持渲染效率。两者之间的唯一区别在于,如果值为 undefined,row.renderValue 将返回该值或 renderFallbackValue,而 row.getValue 将返回该值或 undefined(如果值为 undefined)。

js
// Access data from any of the columns
const firstName = row.getValue('firstName') // read the row value from the firstName column
const renderedLastName = row.renderValue('lastName') // render the value from the lastName column
// Access data from any of the columns
const firstName = row.getValue('firstName') // read the row value from the firstName column
const renderedLastName = row.renderValue('lastName') // render the value from the lastName column

注意:cell.getValuecell.renderValue 分别是 row.getValuerow.renderValue API 的快捷方式。

访问原始行数据

对于每个行对象,您可以通过 row.original 属性访问传递给表实例的原始相应 datarow.original 中的数据不会被列定义中的访问器修改,因此如果您在访问器中进行了任何数据转换,这些转换不会反映在 row.original 对象中。

js
// Access any data from the original row
const firstName = row.original.firstName // { firstName: 'John', lastName: 'Doe' }
// Access any data from the original row
const firstName = row.original.firstName // { firstName: 'John', lastName: 'Doe' }

子行

如果您使用的是分组或展开功能,您的行可能包含子行或父行引用。这将在 展开指南 中更详细地讨论,但这里是处理子行的有用属性和方法的快速概述。

  • row.subRows:行的子行数组。
  • row.depth:行相对于根行数组的深度(如果嵌套或分组)。根级行深度为 0,子行深度为 1,孙子行深度为 2,依此类推。
  • row.parentId:行的父行的唯一 ID(包含此行在其 subRows 数组中的行)。
  • row.getParentRow:返回行的父行(如果存在)。

更多行 API

根据您为表使用的功能,还有许多其他有用的 API 可用于与行进行交互。请参阅每个功能的相应 API 文档或指南了解更多信息。

我们的合作伙伴
Code Rabbit
AG Grid
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。