react 递归生成树形菜单

首先你需要准备一个类似如下的树形json

const lists = [
  {
    key: "2",
    name: "tab2",
    feat1: "",
    children: [
      {
        key: "2-1",
        name: "2-1",
        feat1: "xxxx",
      },
      {
        key: "2-2",
        name: "2-2",
        feat1: "zzzz",
      },
    ],
  },
  {
    key: "3",
    name: "tab3",
    feat1: "",
    children: [
      {
        key: "3-1",
        name: "3-1",
        feat1: "aaaa",
      },
      {
        key: "3-2",
        name: "3-2",
        feat1: "",
        children: [
          {
            key: "3-2-1",
            name: "3-2-1",
            feat1: "qqqq",
          },
          {
            key: "3-2-2",
            name: "3-2-2",
            feat1: "wwww",
          },
        ]
      },
    ],
  },
  {
    name: "tab5",
    feat1: "llll",
    key: "5",
  },
];

然后需要一个递归函数

const genMenu = (dataList: any[]) => {
  return dataList.map((t1) => {
    if (!t1.children) {
      return (
        
          {t1.name}
        
      );
    }
    return {genMenu(t1.children)};
  });
};

最后渲染组件

const newMenu1 = (
  
    {lists.map((t1) => {
      if (!t1.children) {
        return (
          
            {t1.name}
          
        );
      }
      return {genMenu(t1.children)};
    })}
  
);

return (
  
     e.preventDefault()}>
      list menu 
    
  
);

附:效果 codesandbox地址

你可能感兴趣的:(react 递归生成树形菜单)