本快速指南将讨论在 TanStack Table 中检索和与 header 对象交互的不同方法。
表头相当于单元格,但用于表格的 <thead> 部分,而不是 <tbody> 部分。
表头来自表头组,表头组相当于行,但用于表格的 <thead> 部分,而不是 <tbody> 部分。
如果您在表头组中,表头存储在 headerGroup.headers 属性的数组中。通常,您只需遍历此数组即可渲染表头。
<thead>
{table.getHeaderGroups().map(headerGroup => {
return (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => ( // 遍历 headerGroup headers 数组
<th key={header.id} colSpan={header.colSpan}>
{/* */}
</th>
))}
</tr>
)
})}
</thead>
<thead>
{table.getHeaderGroups().map(headerGroup => {
return (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => ( // 遍历 headerGroup headers 数组
<th key={header.id} colSpan={header.colSpan}>
{/* */}
</th>
))}
</tr>
)
})}
</thead>
有多个 table 实例 API 可用于根据您使用的功能检索表头列表。您可能最常使用的 API 是 table.getFlatHeaders,它将返回表格中所有表头的扁平列表,但至少还有十几个其他表头与列可见性和列固定功能一起使用时非常有用。诸如 table.getLeftLeafHeaders 或 table.getRightFlatHeaders 之类的 API 根据您的用例可能会很有用。
表头对象类似于单元格对象,但用于表格的 <thead> 部分,而不是 <tbody> 部分。每个表头对象都可以与 UI 中的 <th> 或类似的单元格元素相关联。header 对象上有一些属性和方法可用于与表格状态交互,并根据表格状态从表格中提取单元格值。
每个表头对象都有一个 id 属性,使其在表格实例中唯一。通常,您只需要此 id 作为 React 键的唯一标识符,或者如果您正在遵循高性能列大小调整示例。
对于没有高级嵌套或分组表头逻辑的简单表头,header.id 将与其父 column.id 相同。但是,如果表头是组列或占位符单元格的一部分,则它将具有一个更复杂的 ID,该 ID 由表头族、深度/表头行索引、列 ID 和表头组 ID 构成。
header 对象上有一些属性仅在表头是嵌套或分组表头结构的一部分时才有用。这些属性包括:
注意:header.index 指的是其在表头组(表头行)中的索引,即其从左到右的位置。它与 header.depth 不同,后者指的是表头组“行索引”。
表头附加了一些更有用的 API,可用于与表格状态交互。其中大多数与列大小调整和调整大小功能有关。有关更多信息,请参阅列大小调整指南。
由于您定义的 header 列选项可以是字符串、jsx 或返回其中任一者的函数,因此渲染表头的最佳方法是使用适配器中的 flexRender 实用程序,它将为您处理所有这些情况。
{headerGroup.headers.map(header => (
<th key={header.id} colSpan={header.colSpan}>
{/* 处理 `header` 的所有可能的表头列定义方案 */}
{flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}
{headerGroup.headers.map(header => (
<th key={header.id} colSpan={header.colSpan}>
{/* 处理 `header` 的所有可能的表头列定义方案 */}
{flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}