You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ant Design 4.20.0+版本侧边栏添加链接方法求助

在Ant Design函数式Menu中添加路由链接的解决方法

针对Ant Design Menu组件的函数式(items配置)写法,以下两种方法可以正常添加路由链接:

方法一:在label中嵌套Link组件(推荐)

直接在items数组的菜单项label字段中渲染React Router的Link组件,代码示例:

import { Menu } from 'antd';
import { SettingOutlined, AppstoreOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';

const items = [
  {
    key: 'SubMenu',
    icon: <SettingOutlined />,
    label: '设置菜单',
    children: [
      {
        key: 'two',
        icon: <AppstoreOutlined />,
        label: <Link to="/target-path">导航二</Link>,
      },
    ],
  },
];

// 渲染Menu组件
<Menu
  mode="inline"
  openKeys={openKeys}
  onOpenChange={onOpenChange}
  style={{ width: 256 }}
  items={items}
/>

这种方式完全兼容React Router的路由机制,点击菜单项会触发路由跳转,且保留单页面应用的特性。

方法二:通过onClick事件手动跳转(适合需额外逻辑的场景)

如果需要在跳转前执行额外逻辑,可以通过Menu的onClick事件处理跳转:

import { Menu } from 'antd';
import { SettingOutlined, AppstoreOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const YourComponent = () => {
  const navigate = useNavigate();

  const handleMenuClick = (e) => {
    // 根据菜单项key判断跳转目标
    if (e.key === 'two') {
      // 执行额外逻辑(如权限校验)
      // ...
      navigate('/target-path');
    }
  };

  const items = [
    {
      key: 'SubMenu',
      icon: <SettingOutlined />,
      label: '设置菜单',
      children: [
        {
          key: 'two',
          icon: <AppstoreOutlined />,
          label: '导航二',
        },
      ],
    },
  ];

  return (
    <Menu
      mode="inline"
      openKeys={openKeys}
      onOpenChange={onOpenChange}
      style={{ width: 256 }}
      items={items}
      onClick={handleMenuClick}
    />
  );
};

注意事项

  • 确保已正确安装并导入react-router-dom相关组件(Link/useNavigate)
  • 如果使用Ant Design Pro框架,可直接在items中配置path字段,Menu会自动关联框架的约定式路由

内容的提问来源于stack exchange,提问作者sharmag 2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:45:37