英文:
How to add custom row in tanstack table v8?
问题
我对tanstack/react table相当新,我需要实现一个带有自定义行的表格,不遵循列定义,有没有好的方法来实现这个/是否可能?
以我的理解,所有行都需要遵循列定义,所以我不确定如何实现这一点。如果我错了,请纠正我。谢谢。
英文:
I'm fairly new to tanstack/react table. I need to implement a table with a custom row that doesn't follow the column definitions, what's a good way to do this/is it possible?
In my understanding, all rows need to follow the column definition, so I'm not sure how to achieve this. Please correct me if I'm wrong. Thank you.
答案1
得分: 2
以下是翻译好的部分:
正确的实现取决于您对自定义行的条件。在您的表格中,应该有类似于这样的内容,其中您获取表格的行:
table.getRowModel().rows
并将它们映射到输出每一行的 <tr>
标签。
<tbody>
{table.getRowModel().rows.map((row, index) => (
row.original.isCustomRow ?
<tr key={row.id}>
<td colSpan={columns.length} className="text-center">
这里是自定义行
</td>
</tr>
:
<tr key={row.id}>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
在上面的片段中,我根据原始对象上的标志插入自定义行。要使其工作,您需要将自定义行插入用于表格的数据中。
还请注意 <td>
上的 colspan
属性,以便该项跨越整行。根据您的需求进行调整。
英文:
The correct implementation depends on the condition you have for the custom row. In your table you should have something similar to this, where you get the rows of the table
table.getRowModel().rows
and map them to output an <tr>
tag for each row.
<tbody>
{table.getRowModel().rows.map((row, index) => (
row.original.isCustomRow ?
<tr key={row.id}>
<td colSpan={columns.length} className="text-center">
Custom Row here
</td>
</tr>
:
<tr key={row.id}>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
In this snippet above I insert a custom Row depending on a flag on the original object. For this to work you need to insert the custom Row inside the data you are using for the table.
Notice also the colspan
attribute on the <td>
, so that the entry spans over the row. Adjust it to your needs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论