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

Material UI v1版本TextField下划线Hover颜色设置无效,求解决方案

解决Material UI 1.x中TextField hover状态下划线颜色失效的问题

嘿,我来帮你搞定这个困扰!在Material UI 1.x版本里,组件的样式类名规范和结构都做了调整,之前针对旧版本写的伪元素选择器自然就不生效了。别担心,我给你两个常用的可行方案:

方案一:使用withStyles高阶组件定制

这种方式适合类组件,也能轻松复用定制后的TextField:

import { TextField, withStyles } from '@material-ui/core';

// 定义自定义样式
const StyledTextField = withStyles({
  root: {
    // 定位到Input的下划线容器
    '& .MuiInput-underline': {
      // 针对hover且非禁用状态的下划线
      '&:hover:not(.Mui-disabled):before': {
        borderBottomColor: 'green', // 替换成你想要的hover颜色
      },
      // 额外补充:如果需要修改focus状态的下划线颜色
      '&:after': {
        borderBottomColor: 'darkgreen',
      }
    }
  }
})(TextField);

// 直接使用定制后的组件
function App() {
  return <StyledTextField label="自定义下划线颜色" />;
}

方案二:使用makeStyles钩子(函数组件推荐)

如果你用的是函数组件,makeStyles会更灵活:

import { makeStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';

const useStyles = makeStyles({
  customTextField: {
    '& .MuiInput-underline:hover:not(.Mui-disabled):before': {
      borderBottomColor: 'green',
    }
  }
});

function MyComponent() {
  const classes = useStyles();
  return <TextField className={classes.customTextField} label="测试输入框" />;
}

为什么旧代码失效?

Material UI 1.x统一了组件的类名规范,旧代码里的$disabled变量被替换成了全局的.Mui-disabled类,同时下划线的容器也有了新的类名.MuiInput-underline,所以必须调整选择器的层级和类名才能命中目标元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:31:55