React + Ant Design 利用递归动态生成菜单栏
自定义菜单配置文件
import {
HomeOutlined,
AppstoreOutlined,
UserOutlined,
SettingOutlined,
BarChartOutlined,
LineChartOutlined,
UnorderedListOutlined,
ApartmentOutlined,
PieChartOutlined,
AreaChartOutlined
} from '@ant-design/icons'
const menuList = [
{
title: '首页',
key: '/home',
icon: HomeOutlined
}, {
title: '商品管理',
key: '/products',
icon: AppstoreOutlined,
children: [{
title: '类别管理',
key: '/category',
icon: ApartmentOutlined,
}, {
title: '增删改查',
key: '/product',
icon: UnorderedListOutlined
}]
}, {
title: '用户管理',
key: '/user',
icon: UserOutlined
}, {
title: '权限设置',
key: '/role',
icon: SettingOutlined
}, {
title: '数据统计',
key: '/statistics',
icon: AreaChartOutlined,
children: [{
title: '柱形图',
key: '/statistics/bar',
icon: BarChartOutlined
}, {
title: '折线图',
key: '/statistics/line',
icon: LineChartOutlined
}, {
title: '饼图',
key: '/statistics/pie',
icon: PieChartOutlined
}]
}
];
export default menuList
菜单组件
import React, { Component } from 'react'
import menuList from './menu-list'
import { withRouter } from 'react-router-dom'
import { Menu } from 'antd'
const { SubMenu } = Menu;
class LeftMenu extends Component {
state = {
openKey: []
};
handleChangeMenu = ({key}) => {
this.props.history.push(key);
};
handleOpenChange = (v) => {
this.setState({
openKey: v
})
};
componentDidMount() {
this.setState({
openKey: [this.openKey]
});
}
createMenuListMap = (list) => {
return list.map((item) => {
if(item.children) {
const path = this.props.location.pathname;
const res = item.children.find(child => path.indexOf(child.key) >= 0);
if(res) this.openKey = item.key;
return (
<SubMenu
key={item.key}
title={
<span>
<item.icon />
<span>{item.title}</span>
</span>
}
>
{
this.createMenuListMap(item.children)
}
</SubMenu>
);
} else {
return (
<Menu.Item key={item.key}>
<Link to={item.key}>
<item.icon />
<span>{item.title}</span>
</Link>
</Menu.Item>
);
}
});
};
render() {
return (
<div className="left-nav">
<Menu
mode="inline"
theme="dark"
onClick={this.handleChangeMenu}
selectedKeys={[this.props.location.pathname]}
onOpenChange={this.handleOpenChange}
openKeys={this.state.openKey}
>
{
this.createMenuListMap(menuList)
}
</Menu>
</div>
)
}
}
export default withRouter(LeftMenu)
如果对 Vue 有深入了解,该方式的原理同样适用于 Vue