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

MUI v5中如何设置ButtonGroup内Button的hover行为保持红色边框

问题原因

MUI v5 的 ButtonGroup 组件为了统一组内按钮的边框衔接效果,会对组内的 outlined 类型按钮的 hover、active、disabled 等状态注入全局统一样式,该样式优先级高于单个 Button 自带的 color="error" 属性对应的状态样式,因此会出现 hover 时边框被覆盖为默认蓝色的问题。

解决方案

方案1:局部覆写(sx属性,MUI官方推荐针对个别场景使用)

直接给需要固定为error色调的Button添加sx属性,手动覆盖所有状态的样式,样式值直接调用theme变量保证和全局主题统一:

<ButtonGroup variant="outlined">
  <Button 
    color="error"
    sx={(theme) => ({
      // 基础状态样式
      color: theme.palette.error.main,
      borderColor: theme.palette.error.main,
      // hover状态样式
      '&:hover': {
        color: theme.palette.error.dark,
        borderColor: theme.palette.error.dark,
        // 可选:保持hover背景色和error主题对应,透明度和MUI默认按钮hover一致
        backgroundColor: `${theme.palette.error.main}14`
      },
      // 点击激活状态样式
      '&:active': {
        color: theme.palette.error.dark,
        borderColor: theme.palette.error.dark
      },
      // 禁用状态样式,不需要可以删除
      '&.Mui-disabled': {
        color: theme.palette.error.light,
        borderColor: theme.palette.error.light
      }
    })}
  >
    Again
  </Button>
  <Button>
    Good
  </Button>
</ButtonGroup>

如果不需要hover时颜色变深,要完全保持和默认状态一致的红色,直接把hover、active里的颜色值都换成theme.palette.error.main即可。

方案2:全局配置(适合项目内所有ButtonGroup内的error按钮统一效果)

如果你需要项目内所有放在ButtonGroup里的outlined类型error按钮都自动应用这个样式,可以在全局主题配置里统一覆写样式,不需要再给单个按钮加sx:

import { createTheme, ThemeProvider } from '@mui/material/styles';

const theme = createTheme({
  components: {
    MuiButton: {
      styleOverrides: {
        root: ({ ownerState, theme }) => {
          // 只匹配ButtonGroup内的outlined类型error按钮
          if (ownerState.color === 'error' && ownerState.variant === 'outlined' && ownerState.grouped) {
            return {
              color: theme.palette.error.main,
              borderColor: theme.palette.error.main,
              '&:hover': {
                color: theme.palette.error.dark,
                borderColor: theme.palette.error.dark,
                backgroundColor: `${theme.palette.error.main}14`
              },
              '&:active': {
                color: theme.palette.error.dark,
                borderColor: theme.palette.error.dark
              }
            };
          }
          return {};
        }
      }
    }
  }
});

// 之后把ThemeProvider包裹在应用根组件即可

内容的提问来源于stack exchange,提问作者Xavier Taylor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:39:01