自己写一个树状结构的递归处理函数

1,196 阅读2分钟

自己写一个树状结构的递归处理函数。

当你的项目没有使用 antd 4.x,用的是 antd 3.x,你就会发现,树状结构的层级是需要自己去写的,那这个时候, 我们就需要用到递归去实现层级了。

官网的是这样的:

<DirectoryTree 
    multiple 
    defaultExpandAll 
    onSelect={this.onSelect} 
    onExpand={this.onExpand}
    > 
    <TreeNode title="parent 0" key="0-0"> 
        <TreeNode title="leaf 0-0" key="0-0-0" isLeaf /> 
        <TreeNode title="leaf 0-1" key="0-0-1" isLeaf /> 
        </TreeNode> <TreeNode title="parent 1" key="0-1"> 
        <TreeNode title="leaf 1-0" key="0-1-0" isLeaf /> 
        <TreeNode title="leaf 1-1" key="0-1-1" isLeaf /> 
    </TreeNode> 
 </DirectoryTree>

页面展示结果:

image.png

每一层都要一个一个的写,而且还是写死的,不是从一个树状数组中取的数据。我们开发过程中肯定是向后端发请求,获取一个树状数组的数据,然后渲染在页面上。那我们应该怎么写呢?

数组:

const list = [
        {title: '一级', key: '0-0',child: [
          {title: '一级  1', key: '0-0-0'},
          {title: '一级  2', key: '0-0-1'},
          {title: '一级  3', key: '0-0-2'},
        ]},
        {title: '二级', key: '0-1',child: [
          {title: '二级  1', key: '0-1-0',child: [
            {title: '二级  1 1', key: '0-1-0-1', child: [
               { title: '二级 1 1 1', key: '0-1-0-1-0', child: [
                { title: '二级 1 1 1 1', key: '0-1-0-1-0-0', child: [
                  {title: '二级 1 1 1 1 1',key: '0-1-0-1-0-0-0'}
                ]}
               ]}
            ]},
            {title: '二级  1 2', key: '0-1-0-2'},
            {title: '二级  1 3', key: '0-1-0-3'},
          ]},
          {title: '二级  2', key: '0-1-1'},
          {title: '二级  3', key: '0-1-2'},
        ]},
        {title: '三级', key: '0-2'},
        
      ]

简单点的实现步骤:

<DirectoryTree
  onSelect={onSelect}
>
  {
    list.map((item=>{
      return <TreeNode title={item.title}  key={item.key}>
                    {item.child  && item.child.map((ele=>{
                      return <TreeNode title={ele.title}  key={ele.key}>
                            </TreeNode>
                    }))}
              </TreeNode>
    }))
  }

</DirectoryTree>

这样写只是一层的效果。

image.png 如果好几层呢? 无限嵌套?代码看起来不太好的亚子,没关系,让我们写一个递归, 就可以实现了。

首先。我们可以先写一个递归函数

const eleHandle = (list: any) =>{
    if(list) {
      return list.map((it:any)=>{
        return <>
        <TreeNode title={it.title} key={it.key}>
         {it.child && eleHandle(it.child)}
        </TreeNode>
        </>
      })
    }
  }

然后,再使用这个函数,让他展示到页面上。

<DirectoryTree
  onSelect={onSelect}
>
  {
    list.map((item=>{
      return  <TreeNode title={item.title}  key={item.key}>
                  // 使用递归函数
                {item.child  && eleHandle(item.child)}
              </TreeNode>
    }))
  }
</DirectoryTree>

接下来再看看我们的页面:

image.png

这样不管有多少级都可以轻松展示啦。