// menuConfig.js 用来配置左侧菜单栏
import {
AppstoreOutlined,
MenuUnfoldOutlined,
MenuFoldOutlined,
PieChartOutlined,
DesktopOutlined,
ContainerOutlined,
MailOutlined,
} from '@ant-design/icons';
const menuList = [
{
title: '首页',
path: '/home',
icon: <PieChartOutlined />
},
{
title: '商品',
path: '/products',
icon: <MailOutlined />,
children: [
{
title: '品类管理',
path: '/category',
icon: <MailOutlined />
},
{
title: '商品管理',
path: '/product',
icon: <MailOutlined />
}
]
},
{
title: '用户管理',
path: '/user',
icon: <MailOutlined />,
},
{
title: '角色管理',
path: '/role',
icon: <MailOutlined />,
},
{
title: '图形管理',
path: '/charts',
icon: <MailOutlined />,
children: [
{
title: '条形图',
path: '/bar',
icon: <MailOutlined />
},
{
title: '折线图',
path: '/line',
icon: <MailOutlined />
},
{
title: '饼状图',
path: '/pie',
icon: <MailOutlined />
}
]
},
]
export default menuList
import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { Menu } from 'antd';
import menuList from '../../config/menuConfig'
import './index.less'
const SubMenu = Menu.SubMenu
class LeftNav extends Component {
getMenuNodes = (menuList) => {
return menuList.reduce((pre, item) => {
if (!item.children) {
pre.push((
<Menu.Item key={item.key} icon={item.icon}>
<Link to={item.key}>{item.title}</Link>
</Menu.Item>
))
} else {
pre.push((
<SubMenu key={item.key} icon={item.icon} title={item.title}>
{this.getMenuNodes(item.children)}
</SubMenu>
))
}
return pre
}, [])
}
render() {
const path = this.props.location.pathname
console.log('render()',path);
return (
<div className="left-nav">
<Link to='/' className="left-nav-header" >
<img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="" />
<h1>后台管理系统</h1>
</Link>
<Menu
mode="inline"
theme="dark"
selectedKeys={[path ]}
>
{this.getMenuNodes(menuList)}
</Menu>
</div>
)
}
}
/*
withRouter高阶组件:
包装非路由组件,返回一个新的组件
新组件向非路由组件传递3个属性:history/location/match
*/
export default withRouter(LeftNav)
当刷新页面时,默认选中菜单项的设置,因为menu的selectedKeys属性存储key值,即我们使用的path路径,我们知道this.props.location.pathname可以取到path的路径,但是当前leftMenu不是路由组件,不能通过this.props.location来取到需要的值,此时我们借助react-router-dom的withRouter
使用:
引入Import{ withRouter } from 'react-router-dom';
export default withRouter(MenuLeft);
export的时候用withRouter包装一下
原文链接:https://blog.csdn.net/youlinaixu/article/details/92085600
原文链接:https://blog.csdn.net/youlinaixu/article/details/92085600