You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Tabulator嵌套表格自定义子行十进制行号格式化方法

React Tabulator 树形表格层级行号实现方案

要实现十进制对齐的层级行号(如1.1、2.1),可以通过自定义格式化函数,利用Tabulator提供的树形行API递归构建行号,替代默认的rownum格式化器。

核心思路

遍历当前行的所有父级节点,依次收集每个节点在同级列表中的位置索引(从1开始),最后将这些索引按层级顺序拼接成带小数点的行号。

具体实现

1. 定义自定义层级行号格式化函数

const hierarchyRowNumFormatter = (cell) => {
  const row = cell.getRow();
  const hierarchyNumbers = [];
  let currentRow = row;

  // 向上遍历所有父级节点,收集层级编号
  while (currentRow) {
    const parentRow = currentRow.getTreeParent();
    if (parentRow) {
      // 获取当前行在父级子节点中的位置(索引从1开始)
      const siblingRows = parentRow.getTreeChildren();
      const currentIndex = siblingRows.indexOf(currentRow) + 1;
      hierarchyNumbers.unshift(currentIndex);
    } else {
      // 根节点,获取在根行列表中的位置
      const rootRows = cell.getTable().getRows(true); // true 仅返回根节点行
      const currentIndex = rootRows.indexOf(currentRow) + 1;
      hierarchyNumbers.unshift(currentIndex);
    }
    currentRow = parentRow;
  }

  return hierarchyNumbers.join('.');
};

2. 在列配置中使用该格式化器

将自定义格式化器替换原来的rownum配置:

const columns = [
  {
    title: '层级行号',
    formatter: hierarchyRowNumFormatter,
    width: 120,
    frozen: true, // 可选:冻结行号列,方便滚动查看
  },
  // 其他列配置示例
  { title: '名称', field: 'name' },
  { title: '描述', field: 'desc' },
];

关键API说明

  • getTreeParent(): 获取当前行的父级行节点
  • getTreeChildren(): 获取父级行的直接子节点列表
  • getRows(true): 获取表格中所有根节点行(忽略子节点)
  • indexOf(row) + 1: 将数组索引(从0开始)转换为行号(从1开始)

效果验证

  • 根节点行号:1、2、3...
  • 一级子节点:1.1、1.2、2.1、2.2...
  • 二级子节点:1.1.1、1.1.2、2.1.1...

内容的提问来源于stack exchange,提问作者Triss Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 06:10:13