本快速指南将讨论在 TanStack Table 中检索和交互 cell 对象的不同方法。
单元格来自 行。 说的够明白了吧?
有多种 row 实例 API 可用于从行中检索适当的单元格,具体取决于你使用的功能。 最常见的是,你将使用 row.getAllCells 或 row.getVisibleCells API(如果你正在使用列可见性功能),但还有一些其他类似的 API 可以使用。
每个单元格对象都可以与 UI 中的 <td> 或类似的单元格元素关联。 cell 对象上有一些属性和方法,可用于与表状态交互并根据表的状态从表中提取单元格值。
每个单元格对象都有一个 id 属性,使其在表实例中是唯一的。 每个 cell.id 都被简单地构造为其父行和列 ID 的联合,并用下划线分隔。
{ id: `${row.id}_${column.id}` }
{ id: `${row.id}_${column.id}` }
在分组或聚合功能期间,cell.id 将附加额外的字符串。
从单元格访问数据值的推荐方法是使用 cell.getValue 或 cell.renderValue API。 使用这些 API 中的任何一个都将缓存访问器函数的结果并保持渲染效率。 两者之间唯一的区别是,如果值未定义,cell.renderValue 将返回该值或 renderFallbackValue,而如果值未定义,cell.getValue 将返回该值或 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 万名开发者。