罗时庚 發表於 2019-6-20 19:06:00

react中递归生成列表

<pre><code class="lang-javascript">import React, {Component} from 'react';
import { Menu, Icon } from 'antd';
import {Link} from 'react-router-dom';
const menuList = [
    {
      title: '首页', // 菜单标题名称
      key: '/home', // 对应的 path
      icon: 'home', // 图标名称
    },
    {
      title: '商品',
      key: '/products',
      icon: 'appstore',
      children: [ // 子菜单列表
            {
                title: '品类管理',
                key: '/category',
                icon: 'bars'
            },
            {
                title: '商品管理',
                key: '/product',
                icon: 'tool'
            },
      ]
    },
    {
      title: '用户管理',
      key: '/user',
      icon: 'user'
    },
    {
      title: '角色管理',
      key: '/role',
      icon: 'safety',
    },
    {
      title: '图形图表',
      key: '/charts',
      icon: 'area-chart',
      children: [
            {
                title: '柱形图',
                key: '/charts/bar',
                icon: 'bar-chart'
            },
            {
                title: '折线图',
                key: '/charts/line',
                icon: 'line-chart'
            },
            {
                title: '饼图',
                key: '/charts/pie',
                icon: 'pie-chart'
            },
      ]
    },
];


const { SubMenu }= Menu;
class LeftMenu extends Component {
    getMenuNodes = (menuList) =&gt; {
      return menuList.map(item =&gt; {
         if (!item.children) {
               return (
                   &lt;Menu.Item key={item.key}&gt;
                     &lt;Link to={item.key}&gt;
                           &lt;Icon type={item.icon} /&gt;
                           &lt;span&gt;{item.title}&lt;/span&gt;
                     &lt;/Link&gt;
                   &lt;/Menu.Item&gt;
               );
         }else {
               return (&lt;SubMenu
                   key={item.key}
                   title={
                     &lt;span&gt;
                &lt;Icon type={item.icon} /&gt;
                &lt;span&gt;{item.title}&lt;/span&gt;
            &lt;/span&gt;
                   }
               &gt;
                   {
                     this.getMenuNodes(item.children)
                   }
               &lt;/SubMenu&gt;);
         }
      });
    };

    render() {
      return (
            &lt;Menu
                defaultSelectedKeys={['1']}
                defaultOpenKeys={['sub1']}
                mode="inline"
                theme="dark"
            &gt;
                {
                  this.getMenuNodes(MenuList)
                }
            &lt;/Menu&gt;
      )
    }
}

export default LeftMenu;
</code></pre><br><br>
来源:https://www.cnblogs.com/korea/p/11060687.html
頁: [1]
查看完整版本: react中递归生成列表