标准的 Menu菜单

key不能相同,否则会选中多个

  1. <Menu theme="dark" defaultSelectedKeys={['1']} mode="inline">
  2. <Menu.Item key="1" icon={<PieChartOutlined />}>
  3. Option 1
  4. </Menu.Item>
  5. <SubMenu key="sub1" icon={<UserOutlined />} title="User">
  6. <Menu.Item key="3">Tom</Menu.Item>
  7. <Menu.Item key="4">Bill</Menu.Item>
  8. <Menu.Item key="5">Alex</Menu.Item>
  9. </SubMenu>
  10. <Menu.Item key="9" icon={<FileOutlined />}>
  11. Files
  12. </Menu.Item>
  13. </Menu>

递归组件

递归组件动态渲染
image.png
注意:如果把 MenuItem组件抽离为子组件会丢失样式,渲染结果与Menu组件不一样

  1. import React from 'react';
  2. import { Menu } from 'antd';
  3. import { UserOutlined } from '@ant-design/icons';
  4. import router from './menu';
  5. const { SubMenu, Item } = Menu;
  6. function MenuItem() {
  7. return (
  8. <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
  9. {recursiveMenu(router)}
  10. </Menu>
  11. );
  12. }
  13. export default MenuItem;
  14. function recursiveMenu(data) {
  15. return data.map(item => {
  16. if (item?.children?.length) {
  17. return (
  18. <SubMenu
  19. key={item.key}
  20. icon={<UserOutlined/>}
  21. title={item.name}
  22. >
  23. {/*递归渲染*/}
  24. {recursiveMenu(item.children)}
  25. </SubMenu>
  26. );
  27. }
  28. // 一级菜单
  29. return (
  30. <Item key={item.key} icon={<UserOutlined/>}>
  31. {item.name}
  32. </Item>
  33. );
  34. });
  35. }

menu.js

  1. const router = [
  2. {
  3. name: '前端开发',
  4. path: '/web',
  5. key: 'web',
  6. icon: 'UserOutlined',
  7. children: [
  8. {
  9. name: 'React',
  10. path: '/web/react',
  11. key: 'react',
  12. exact: true,
  13. component: () => import('@/routes/react'),
  14. },
  15. {
  16. name: 'vue',
  17. path: '/web/vue',
  18. key: 'vue',
  19. exact: true,
  20. component: () => import('@/routes/vue'),
  21. }
  22. ]
  23. },
  24. {
  25. name: '项目经理',
  26. path: '/pmp',
  27. key: 'pmp',
  28. children: [
  29. {
  30. name: 'Prince2',
  31. path: '/pmp/prince2',
  32. key: 'prince2',
  33. exact: true,
  34. component: () => import('@/routes/prince2'),
  35. },
  36. ]
  37. },
  38. {
  39. name: '分布式',
  40. path: '/cluster',
  41. key: 'cluster',
  42. exact: true,
  43. component: () => import('@/routes/cluster'),
  44. }
  45. ];
  46. export default router