标准的 Menu菜单
key不能相同,否则会选中多个
<Menu theme="dark" defaultSelectedKeys={['1']} mode="inline">
<Menu.Item key="1" icon={<PieChartOutlined />}>
Option 1
</Menu.Item>
<SubMenu key="sub1" icon={<UserOutlined />} title="User">
<Menu.Item key="3">Tom</Menu.Item>
<Menu.Item key="4">Bill</Menu.Item>
<Menu.Item key="5">Alex</Menu.Item>
</SubMenu>
<Menu.Item key="9" icon={<FileOutlined />}>
Files
</Menu.Item>
</Menu>
递归组件
递归组件动态渲染
注意:如果把 MenuItem组件抽离为子组件会丢失样式,渲染结果与Menu组件不一样
import React from 'react';
import { Menu } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import router from './menu';
const { SubMenu, Item } = Menu;
function MenuItem() {
return (
<Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
{recursiveMenu(router)}
</Menu>
);
}
export default MenuItem;
function recursiveMenu(data) {
return data.map(item => {
if (item?.children?.length) {
return (
<SubMenu
key={item.key}
icon={<UserOutlined/>}
title={item.name}
>
{/*递归渲染*/}
{recursiveMenu(item.children)}
</SubMenu>
);
}
// 一级菜单
return (
<Item key={item.key} icon={<UserOutlined/>}>
{item.name}
</Item>
);
});
}
menu.js
const router = [
{
name: '前端开发',
path: '/web',
key: 'web',
icon: 'UserOutlined',
children: [
{
name: 'React',
path: '/web/react',
key: 'react',
exact: true,
component: () => import('@/routes/react'),
},
{
name: 'vue',
path: '/web/vue',
key: 'vue',
exact: true,
component: () => import('@/routes/vue'),
}
]
},
{
name: '项目经理',
path: '/pmp',
key: 'pmp',
children: [
{
name: 'Prince2',
path: '/pmp/prince2',
key: 'prince2',
exact: true,
component: () => import('@/routes/prince2'),
},
]
},
{
name: '分布式',
path: '/cluster',
key: 'cluster',
exact: true,
component: () => import('@/routes/cluster'),
}
];
export default router