框架
版本
企业版

行指南

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 中的任何一个都将缓存访问器函数的结果,并保持渲染效率。 两者之间唯一的区别是,如果值未定义,row.renderValue 将返回该值或 renderFallbackValue,而 row.getValue 将返回该值,如果值未定义,则返回 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 文档或指南。

订阅 Bytes

您的每周 JavaScript 新闻。 每周一免费发送给超过 100,000 名开发人员。

Bytes

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