如何在tanstack table v8中添加自定义行?

huangapple go评论82阅读模式
英文:

How to add custom row in tanstack table v8?

问题

我对tanstack/react table相当新,我需要实现一个带有自定义行的表格,不遵循列定义,有没有好的方法来实现这个/是否可能?

以我的理解,所有行都需要遵循列定义,所以我不确定如何实现这一点。如果我错了,请纠正我。谢谢。

如何在tanstack table v8中添加自定义行?

英文:

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.

如何在tanstack table v8中添加自定义行?

答案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 &lt;tr&gt; tag for each row.

&lt;tbody&gt;
        {table.getRowModel().rows.map((row, index) =&gt; (
          row.original.isCustomRow ?
            &lt;tr key={row.id}&gt;
              &lt;td colSpan={columns.length} className=&quot;text-center&quot;&gt;
                Custom Row here
              &lt;/td&gt;
            &lt;/tr&gt;
            :
            &lt;tr key={row.id}&gt;
              {row.getVisibleCells().map(cell =&gt; (
                &lt;td key={cell.id}&gt;
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                &lt;/td&gt;
              ))}
            &lt;/tr&gt;

        ))}
&lt;/tbody&gt;

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 &lt;td&gt;, so that the entry spans over the row. Adjust it to your needs.

huangapple
  • 本文由 发表于 2023年4月4日 09:29:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定