react的antd左侧菜单及刷新选中状态

本文详细介绍了如何在React应用中使用Ant Design库创建左侧菜单,并在页面刷新后保持菜单选中状态。通过利用React的状态管理和Antd的Menu组件特性,实现动态设置菜单高亮。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据格式
[
    {
        "title": "首页",
        "icon": "home",
        "path": "/home"
    },
    {
        "title": "商品",
        "icon": "home",
        "path": "/catalogProduct",
        "children": [
            {
                "title": "品类管理",
                "icon": "home",
                "path": "/catalog"
            },
            {
                "title": "商品管理",
                "icon": "home",
                "path": "/product"
            }
        ]
    },
    {
        "title": "用户管理",
        "icon": "user",
        "path": "/user"
    },
    {
        "title": "角色管理",
        "icon": "role",
        "path": "/role"
    },
    {
        "title": "图形图标",
        "icon": "home",
        "path": "/pieline",
        "children": [
            {
                "title": "饼图",
                "icon": "home",
                "path": "/pie"
            },
            {
                "title": "折线图",
                "icon": "home",
                "path": "/line"
            }
        ]
    }
]
getMenuNodes = (MenuList) => {
    return MenuList.map(item => {
      if (!item.children) {
        return (
          <Menu.Item key={item.path}>
            <Link to={item.path}>
              <Icon type={item.icon} />
              <span>{item.title}</span>
            </Link>
          </Menu.Item>
        )
      } else {
        return (
          <SubMenu
            key={item.path}
            title={
              <span>
                <Icon type={item.icon} />
                <span>{item.title}</span>
              </span>
            }>
              {this.getMenuNodes(item.children)}
            </SubMenu>
        )
      }
    })
  }
  render() {
    return (
      <div className='MenuLeft'>
        <Menu
          mode="inline"
          theme="dark"
        >
          {
            this.getMenuNodes(config.menuList)
          }
        </Menu>
      </div>
    );
  }
当刷新页面时,默认选中菜单项的设置,因为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包装一下

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值