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

如何在React中自定义Antd v5+的每个菜单项?

修改Antd Menu部分菜单项样式的几种方法

方法1:直接给指定菜单项添加inline样式

利用菜单项支持的style属性(属于React元素通用属性,文档未单独列出但可直接使用),针对特定key的项设置样式:

const items1: MenuProps['items'] = ['Personal', 'Bisnis', 'Masuk'].map((key) => {
  const baseProps = { key, label: `${key}` };
  // 给'Masuk'项单独设置样式
  if (key === 'Masuk') {
    baseProps.style = {
      backgroundColor: '#165DFF',
      borderRadius: '8px',
      padding: '0 16px',
      color: '#fff'
    };
  }
  return baseProps;
});

<Menu
  theme="dark"
  mode="horizontal"
  items={items1}
  style={{ flex: 1, minWidth: 0, justifyContent: 'end', background: 'transparent', color: 'white' }}
/>

方法2:使用自定义类名+全局CSS

适合需要定制hover、active等复杂状态样式的场景:

首先给目标菜单项添加自定义类名:

const items1: MenuProps['items'] = ['Personal', 'Bisnis', 'Masuk'].map((key) => ({
  key,
  label: `${key}`,
  className: key === 'Masuk' ? 'special-menu-item' : ''
}));

然后在全局CSS文件中编写样式(部分场景需要!important覆盖Antd默认样式):

.special-menu-item {
  background-color: #165DFF !important;
  border-radius: 8px !important;
  color: #fff !important;
}

/* 鼠标悬停时的样式 */
.special-menu-item:hover {
  background-color: #4080FF !important;
}

方法3:自定义Label渲染

通过将label替换为带样式的容器,更灵活控制显示区域:

const items1: MenuProps['items'] = ['Personal', 'Bisnis', 'Masuk'].map((key) => ({
  key,
  label: (
    <div 
      style={{
        padding: '8px 16px',
        borderRadius: key === 'Masuk' ? '8px' : '0',
        backgroundColor: key === 'Masuk' ? '#165DFF' : 'transparent',
        color: key === 'Masuk' ? '#fff' : 'inherit'
      }}
    >
      {key}
    </div>
  )
}));

补充说明

Antd Menu的菜单项对象支持React元素的通用属性(如style、className),即使文档未单独列出,也可以直接使用这些属性来定制样式。

内容的提问来源于stack exchange,提问作者Marselino Widis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:57:28