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