本快速指南将讨论在 TanStack Table 中检索和操作 单元格 对象的不同方法。
单元格来自 行。不多说,对吧?
根据你正在使用的功能,有多种 行 实例 API 可用于从行中检索相应的单元格。最常见的是,你将使用 row.getAllCells 或 row.getVisibleCells API(如果你正在使用列可见性功能),但也有一些其他类似的 API 可供使用。
每个单元格对象都可以与 UI 中的 <td> 或类似的单元格元素相关联。单元格对象上有一些属性和方法可用于与表格状态交互,并根据表格状态从表格中提取单元格值。
每个单元格对象都有一个 id 属性,使其在表实例中唯一。每个 cell.id 简单地由其父行 ID 和列 ID 组合而成,并用下划线分隔。
{ id: `${row.id}_${column.id}` }
{ id: `${row.id}_${column.id}` }
在分组或聚合功能期间,cell.id 将附加额外的字符串。
访问单元格数据值的推荐方法是使用 cell.getValue 或 cell.renderValue API。使用其中任何一个 API 都将缓存访问器函数的结果并保持渲染效率。两者之间的唯一区别是 cell.renderValue 将返回值或 renderFallbackValue(如果值为 undefined),而 cell.getValue 将返回值或 undefined(如果值为 undefined)。
注意:cell.getValue 和 cell.renderValue API 分别是 row.getValue 和 row.renderValue API 的快捷方式。
// Access data from any of the columns
const firstName = cell.getValue('firstName') // read the cell value from the firstName column
const renderedLastName = cell.renderValue('lastName') // render the value from the lastName column
// Access data from any of the columns
const firstName = cell.getValue('firstName') // read the cell value from the firstName column
const renderedLastName = cell.renderValue('lastName') // render the value from the lastName column
由于每个单元格对象都与其父行相关联,因此你可以使用 cell.row.original 访问你的表格所使用的任何原始行中的数据。
// Even if we are in the scope of a different cell, we can still access the original row data
const firstName = cell.row.original.firstName // { firstName: 'John', lastName: 'Doe' }
// Even if we are in the scope of a different cell, we can still access the original row data
const firstName = cell.row.original.firstName // { firstName: 'John', lastName: 'Doe' }
根据你为表格使用的功能,有几十个有用的 API 可用于与单元格交互。有关更多信息,请参阅每个功能的相应 API 文档或指南。
你可以直接使用 cell.renderValue 或 cell.getValue API 来渲染你的表格单元格。但是,这些 API 只会输出原始单元格值(来自访问器函数)。如果你在使用 cell: () => JSX 列定义选项,你将需要使用适配器中的 flexRender API 工具。
使用 flexRender API 将允许单元格正确渲染,并包含任何额外的标记或 JSX,并且它将使用正确的参数调用回调函数。
import { flexRender } from '@tanstack/react-table'
const columns = [
{
accessorKey: 'fullName',
cell: ({ cell, row }) => {
return <div><strong>{row.original.firstName}</strong> {row.original.lastName}</div>
}
//...
}
]
//...
<tr>
{row.getVisibleCells().map(cell => {
return <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
})}
</tr>
import { flexRender } from '@tanstack/react-table'
const columns = [
{
accessorKey: 'fullName',
cell: ({ cell, row }) => {
return <div><strong>{row.original.firstName}</strong> {row.original.lastName}</div>
}
//...
}
]
//...
<tr>
{row.getVisibleCells().map(cell => {
return <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
})}
</tr>
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。