本快速指南将讨论在 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 都将缓存访问器函数的结果并保持渲染效率。两者之间的唯一区别在于,如果值为 undefined,row.renderValue 将返回该值或 renderFallbackValue,而 row.getValue 将返回该值或 undefined(如果值为 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 资讯。每周一免费发送给超过 10 万开发者。