MUI 5中如何使用$符号覆盖样式?TextField悬停颜色修改失效求解
MUI 5 TextField全局悬停样式配置方案
原有代码失效原因
- MUI 5 已移除MUI 4版本中
$disabled、$focused、$error这类内部状态变量的引用语法,原有选择器无法匹配对应元素状态 - 需根据你使用的
TextField变体选择对应组件配置,不同变体对应的底层组件如下:
- underline(下划线变体):对应
MuiInput - outlined(描边变体):对应
MuiOutlinedInput - filled(填充变体):对应
MuiFilledInput
修正后的全局主题配置代码
以下为适配MUI 5的写法,以你使用的underline变体为例:
const theme = createTheme({ components: { MuiInputLabel: { styleOverrides: { root: { color: arcBlue, fontSize: '1rem', }, }, }, MuiInput: { styleOverrides: { underline: { '&::before': { borderBottom: `2px solid ${arcBlue}`, }, // 替换原有$状态引用为MUI 5全局状态类 '&:hover:not(.Mui-disabled):not(.Mui-focused):not(.Mui-error)::before': { borderBottom: `2px solid ${arcGrey}`, }, }, }, }, // 若使用outlined变体,新增以下配置即可 MuiOutlinedInput: { styleOverrides: { root: { '&:hover:not(.Mui-disabled):not(.Mui-focused):not(.Mui-error) .MuiOutlinedInput-notchedOutline': { borderColor: arcGrey, } } } } }, });
生效前提
配置完成后需使用ThemeProvider组件将自定义主题包裹你的应用根组件,全局样式配置才能生效。
内容的提问来源于stack exchange,提问作者Diego Franco
相关产品推荐
相关产品推荐

