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

如何在Material-UI自定义主题中覆盖OutlinedInput聚焦状态边框色?

如何修改Material-UI OutlinedInput组件聚焦状态下的边框颜色?

嘿,这个问题我之前也折腾过!你已经在自定义主题里配置了默认边框颜色,要调整聚焦状态的样式,只需要在MuiOutlinedInput的overrides里补充聚焦状态的规则就可以搞定。

Material-UI的组件状态是靠添加特定类名实现的,当OutlinedInput处于聚焦状态时,它的根元素会被加上Mui-focused类,我们可以通过这个类精准定位到内部的notchedOutline元素,覆盖它的边框颜色。

修改后的完整主题代码如下:

import { createMuiTheme } from '@material-ui/core/styles';
import colors from './your-colors-path'; // 替换成你的颜色文件路径

export const defaultTheme = createMuiTheme({ 
  palette: { 
    primary: { 
      main: colors.primary, 
      contrastText: colors.white, 
    }, 
    // 你的其他调色板配置
  }, 
  typography: { 
    // 你的排版配置
  }, 
  overrides: { 
    MuiButton: { 
      outlinedPrimary: { 
        color: colors.text, 
      }, 
    }, 
    MuiInput: { 
      underline: { 
        '&::before': { 
          borderBottomColor: colors.grey, 
        }, 
        '&::after': { 
          borderBottomColor: colors.greyDark, 
        } 
      }, 
    }, 
    MuiOutlinedInput: { 
      notchedOutline: { 
        borderColor: colors.grey, // 默认状态下的边框颜色
      },
      // 新增聚焦状态的样式规则
      '&.Mui-focused .notchedOutline': {
        borderColor: colors.greyDark, // 这里设置你想要的聚焦边框颜色
      }
    } 
  } 
});

简单说下原理:

  • 我们在MuiOutlinedInput的顶级样式里添加了&.Mui-focused .notchedOutline选择器,能精准匹配到聚焦状态下的边框元素
  • 把borderColor换成你需要的颜色值就行,比如你之前用的colors.greyDark或者其他自定义色彩

这样配置后,用户点击或聚焦OutlinedInput组件时,边框颜色就会切换成你设置的聚焦色啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:17:30