React树形结构列表中的层级编号展示

在hzero项目上遇到这么一个需求:树级列表中编号需要体现父子关系。例如:对于节点2,其子节点编号则为2.1、2.2、2.3, 子节点的子节点编号则为2.1.1、2.2.1、2.3.1,以此类推。


image

后台返回的数据格式如下:

[{
    "wbsLineId": 0,
    "limitTime": 45,
    "startDate": "2019-01-01 00:00:00",
    "endDate": "2019-12-31 00:00:00"
}, {
    "children": [{
        "children": [{
            "levelNumber": 2,
            "parentTaskName": "接洽",
            "taskName": "立项",
        }],
        "levelNumber": 1,
        "parentTaskName": "2019042901名称",
        "taskName": "接洽",
    }, {
        "children": [{
            "levelNumber": 2,
            "parentTaskName": "谈判",
            "taskName": "图纸立项",
            }],
        }],
        "levelNumber": 1,
        "parentTaskName": "2019042901名称",
        "taskName": "谈判",
        "childrenCount": 1
    }, {
        "levelNumber": 1,
        "parentTaskName": "2019042901名称",
        "taskName": "签约",
    }],
    "levelNumber": 0,
    "taskName": "2019042901名称",
    "childrenCount": 3
}]

实现方法:
递归遍历树,设置节点在当前层级的位置关系,即对同一层级的节点进行编号,形如1、2、3、4。然后,通过map对象保存节点所在路径上编号,map的格式如下:


levelMap

最后,在render方法中根据id取到相应的编号路径数组,然后把数组转换为相应字符串即可满足需求。

献上关键代码:
遍历树方法,主要对现在项目上的遍历方法进行改造,添加了count参数(统计同一层级的编号)

export function renderTreeData(collections = [], levelPath = {}, count = 0) {
  const pathMap = levelPath;
  let tempCount = count;
  const treeList = collections.map(item => {
    const temp = item;
    pathMap[temp.wbsLineId] = [...(pathMap[temp.parentLineId] || []), temp.wbsLineId];
    if (temp.children) {
      temp.children = [...renderTreeData(temp.children || [], pathMap, 0).treeList];
    }
    tempCount += 1;
    return { ...temp, _order: tempCount };
  });
  return {
    treeList,
    pathMap,
  };
}

保存map对象方法:

export function setLevel(collections, levelPath = {}) {
  const levelMap = levelPath;
  // eslint-disable-next-line guard-for-in
  for (const i in collections) {
    const item = collections[i];
    levelMap[item.wbsLineId] = [...(levelMap[item.parentLineId] || []), item._order];
    if (item.children) {
      setLevel(item.children, levelMap);
    }
  }
  return 

render时取相应的编号数组并转换为要求的字符串

const list = levelMap[record.wbsLineId];
levelNumber = list.toString().replace(/,/g, '.');

你可能感兴趣的:(React树形结构列表中的层级编号展示)