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

Ant Design Menu组件onClick事件参数类型修正问题

解决Antd Menu组件TypeScript类型错误问题

问题根源

你遇到的两个错误核心原因:

  • 代码未导入useState钩子,React无法识别该API
  • 错误将Menu点击事件参数指定为原生MouseEvent类型,而Antd Menu的点击事件参数是其封装的MenuInfo类型,并非原生鼠标事件

修复步骤

  1. 补全React钩子导入
    在文件顶部添加useState的导入语句:

    import { useState } from 'react';
    
  2. 正确指定点击事件参数类型
    Antd已为MenuProps['onClick']定义好完整类型,无需手动指定参数类型即可自动推导;若要显式声明,可导入MenuInfo类型:

    import type { MenuProps, MenuInfo } from 'antd';
    

修复后的完整代码

import { useState } from 'react';
import { AppstoreOutlined, MailOutlined, SettingOutlined } from '@ant-design/icons';
import type { MenuProps, MenuInfo } from 'antd';
import { Menu } from 'antd';

const items: MenuProps['items'] = [
  {
    label: 'Navigation One',
    key: 'mail',
    icon: <MailOutlined />,
  },
  {
    label: 'Navigation Two',
    key: 'app',
    icon: <AppstoreOutlined />,
    disabled: true,
  },
  {
    label: 'Navigation Three - Submenu',
    key: 'SubMenu',
    icon: <SettingOutlined />,
    children: [
      {
        type: 'group',
        label: 'Item 1',
        children: [
          {
            label: 'Option 1',
            key: 'setting:1',
          },
          {
            label: 'Option 2',
            key: 'setting:2',
          },
        ],
      },
      {
        type: 'group',
        label: 'Item 2',
        children: [
          {
            label: 'Option 3',
            key: 'setting:3',
          },
          {
            label: 'Option 4',
            key: 'setting:4',
          },
        ],
      },
    ],
  },
  {
    label: (
      <a href="https://ant.design" target="_blank" rel="noopener noreferrer">
        Navigation Four - Link
      </a>
    ),
    key: 'alipay',
  },
];

const App: React.FC = () => {
  const [current, setCurrent] = useState('mail');

  // 方式1:利用类型推导,无需手动指定参数类型
  const onClick: MenuProps['onClick'] = (e) => {
    console.log('click ', e);
    setCurrent(e.key);
  };

  // 方式2:显式指定MenuInfo类型
  // const onClick = (e: MenuInfo) => {
  //   console.log('click ', e);
  //   setCurrent(e.key);
  // };

  return <Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" items={items} />;
};

export default App;

关键说明

Antd Menu的点击事件参数e是封装后的MenuInfo对象,包含key、keyPath等自定义属性,并非原生鼠标事件,因此不能用React.MouseEvent定义类型。使用MenuProps['onClick']或MenuInfo类型可让TypeScript自动识别参数结构,避免类型错误。

内容的提问来源于stack exchange,提问作者Priyavart Rajain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:15:44