本快速指南将讨论在 TanStack Table 中检索行对象并与之交互的不同方法。
您可以使用多个 table 实例 API 从表格实例中检索行。
如果您需要通过 id 访问特定行,则可以使用 table.getRow 表格实例 API。
const row = table.getRow(rowId)
const row = table.getRow(rowId)
table 实例生成 row 对象,并将它们存储在名为 “行模型” 的有用数组中。 这在行模型指南中进行了更详细的讨论,但以下是您可能访问行模型的最常见方式。
<tbody>
{table.getRowModel().rows.map(row => (
<tr key={row.id}>
{/* ... */}
</tr>
))}
</tbody>
<tbody>
{table.getRowModel().rows.map(row => (
<tr key={row.id}>
{/* ... */}
</tr>
))}
</tbody>
const selectedRows = table.getSelectedRowModel().rows
const selectedRows = table.getSelectedRowModel().rows
每个行对象都包含行数据和许多 API,用于与表格状态交互或根据表格状态从行中提取单元格。
每个行对象都有一个 id 属性,使其在表格实例中是唯一的。 默认情况下,row.id 与行模型中创建的 row.index 相同。 但是,使用来自行数据的唯一标识符覆盖每个行的 id 可能很有用。 您可以使用 getRowId 表格选项来执行此操作。
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.getValue 或 row.renderValue API。 使用这两个 API 中的任何一个都将缓存访问器函数的结果,并保持渲染效率。 两者之间唯一的区别是,如果值未定义,row.renderValue 将返回该值或 renderFallbackValue,而 row.getValue 将返回该值,如果值未定义,则返回 undefined。
// 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.getValue 和 cell.renderValue 分别是 row.getValue 和 row.renderValue API 的快捷方式。
对于每个行对象,您都可以通过 row.original 属性访问传递给表格实例的原始对应 data。 row.original 中的任何数据都不会被列定义中的访问器修改,因此,如果您在访问器中进行任何类型的数据转换,这些都不会反映在 row.original 对象中。
// 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' }
如果您正在使用分组或展开功能,则您的行可能包含子行或父行引用。 这在展开指南中进行了更详细的讨论,但以下是用于处理子行的有用属性和方法的快速概述。
根据您为表格使用的功能,还有数十个更有用的 API 用于与行交互。 有关更多信息,请参阅每个功能的相应 API 文档或指南。
您的每周 JavaScript 新闻。 每周一免费发送给超过 100,000 名开发人员。