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

Material UI:如何在主题中设置输入框聚焦颜色

设置Material-UI输入框焦点颜色的正确方式

你之前的代码没生效,是因为MUI输入框的焦点样式并不直接继承action.focus配置——这个属性主要用于按钮等通用组件的焦点状态。要修改输入框的焦点颜色,需要针对具体的输入框组件(比如OutlinedInput、FilledInput)在主题里覆盖样式,或者局部自定义样式。

下面是几种可行的方案:

方案一:全局主题覆盖(以Outlined类型输入框为例)

如果你的项目里用的是带边框的输入框(variant="outlined"),可以在主题中针对MuiOutlinedInput组件做样式覆盖:

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

const theme = createTheme({
  components: {
    MuiOutlinedInput: {
      styleOverrides: {
        root: {
          // 修改焦点时的边框颜色
          '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
            borderColor: '#cc0000',
          },
          // 修改焦点时的标签颜色
          '&.Mui-focused .MuiInputLabel-root': {
            color: '#cc0000',
          },
        },
      },
    },
  },
});

// 用ThemeProvider包裹你的应用组件
function App() {
  return (
    <ThemeProvider theme={theme}>
      <TextField label="测试输入框" variant="outlined" />
    </ThemeProvider>
  );
}

方案二:针对其他类型输入框的调整

如果你用的是填充式(variant="filled")或标准式(variant="standard")输入框,需要对应修改不同的组件样式:

填充式输入框:

const theme = createTheme({
  components: {
    MuiFilledInput: {
      styleOverrides: {
        root: {
          '&.Mui-focused:after': {
            borderBottomColor: '#cc0000', // 焦点下划线颜色
          },
          '&.Mui-focused .MuiInputLabel-root': {
            color: '#cc0000', // 焦点标签颜色
          },
        },
      },
    },
  },
});

标准式输入框:

const theme = createTheme({
  components: {
    MuiInput: {
      styleOverrides: {
        root: {
          '&.Mui-focused:after': {
            borderBottomColor: '#cc0000',
          },
          '&.Mui-focused .MuiInputLabel-root': {
            color: '#cc0000',
          },
        },
      },
    },
  },
});

方案三:局部自定义单个输入框样式

如果只需要修改某一个输入框的焦点样式,可以直接通过sx属性设置:

<TextField
  label="测试输入框"
  variant="outlined"
  sx={{
    '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
      borderColor: '#cc0000',
    },
    '&.Mui-focused .MuiInputLabel-root': {
      color: '#cc0000',
    },
  }}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 08:37:46