用react实现简单的树组件

513 阅读1分钟

树组件思路

1、function的递归,一个function也可以看作一个组件,父跟子需要有共同结构。
2、用到的layout组件,从该组件的搭配方式获取进行思考。

初始准备

1、引入react,跟reactdom的cdn;
2、导出createElement方法,方法如下;
let h = React.createElement

代码

//单棵树父组件的处理
const Nav = function(props) {
      let children = props.children
      //创建了基础信息展示
      let head = h('div', null, [props.name, children ? '▼' : null])
      //创建子组件的容器
      let Child = h('ul', null, children)
      return h('div', null, [head, children && Child])
}
//子组件的处理
const NavItem = function (props) {
      let children = props.children
      //如果子组件也存在子项,那么当前的节点作为父节点开始执行
      return h('li', null, [children ? h(Nav, { ...props }) : props.name])
}
//默认生成一颗树
 let treeList = [
        {
          name: '首页',
          id: 1,
          pid: null,
        },
        {
          name: '城市数据',
          id: 2,
          pid: null,
          children: [
            {
              name: 'hello',
              id: 2 - 1,
              pid: 2,
              children: [
                {
                  name: 'heChild',
                  id: 2 - 1 - 1,
                  pid: 2 - 1,
                },
                {
                  name: '2heChild2',
                  id: 2 - 1 - 2,
                  pid: 2 - 1,
                },
              ],
            },
            {
              name: 'hellossssss',
              id: 2 - 2,
              pid: 2,
            },
          ],
        },
      ];
 //根据数据生成真实的组件     
 const NavList = function () {
    function createTree(tree, deepth = 0) {
      return tree.map((v) => {
        return h(
          deepth == 0 ? Nav : NavItem,
          {
            ...v,
          },
          v.children ? createTree(v.children, ++deepth) : null
        );
      });
    }
    return h('div', null, createTree(treeList));
 } 
 
//将数据进行渲染
ReactDOM.render(h(NavList), document.getElementById('app'));

效果

结束

  • 书写的功能很基础,仅有展示作用
  • 如果有更好的组件思路,希望大家留在评论区
  • 觉得可以,给个赞。谢谢