单元格指南

API

单元格 API

单元格指南

本快速指南将讨论在 TanStack Table 中检索和交互 cell 对象的不同方法。

从哪里获取单元格

单元格来自 。 说的够明白了吧?

有多种 row 实例 API 可用于从行中检索适当的单元格,具体取决于你使用的功能。 最常见的是,你将使用 row.getAllCellsrow.getVisibleCells API(如果你正在使用列可见性功能),但还有一些其他类似的 API 可以使用。

单元格对象

每个单元格对象都可以与 UI 中的 <td> 或类似的单元格元素关联。 cell 对象上有一些属性和方法,可用于与表状态交互并根据表的状态从表中提取单元格值。

单元格 ID

每个单元格对象都有一个 id 属性,使其在表实例中是唯一的。 每个 cell.id 都被简单地构造为其父行和列 ID 的联合,并用下划线分隔。

js
{ id: `${row.id}_${column.id}` }
{ id: `${row.id}_${column.id}` }

在分组或聚合功能期间,cell.id 将附加额外的字符串。

单元格父对象

每个单元格都存储对其父 对象的引用。

访问单元格值

从单元格访问数据值的推荐方法是使用 cell.getValuecell.renderValue API。 使用这些 API 中的任何一个都将缓存访问器函数的结果并保持渲染效率。 两者之间唯一的区别是,如果值未定义,cell.renderValue 将返回该值或 renderFallbackValue,而如果值未定义,cell.getValue 将返回该值或 undefined

注意: cell.getValuecell.renderValue API 分别是 row.getValuerow.renderValue API 的快捷方式。

js
// 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 访问你在表中使用的原始行中的任何数据。

js
// 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 用于与单元格交互。 有关更多信息,请参阅每个功能的各自 API 文档或指南。

单元格渲染

你可以只使用 cell.renderValuecell.getValue API 来渲染表的单元格。 但是,这些 API 只会输出原始单元格值(来自访问器函数)。 如果你正在使用 cell: () => JSX 列定义选项,你将需要使用适配器中的 flexRender API 实用程序。

使用 flexRender API 将允许使用任何额外的标记或 JSX 正确渲染单元格,并且它将使用正确的参数调用回调函数。

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>
订阅 Bytes

你的每周 JavaScript 新闻。 每周一免费发送给超过 10 万名开发者。

Bytes

没有垃圾邮件。 随时取消订阅。