如何自定义material-ui TextField Input underline:after?

Ken*_*enB 5 reactjs material-ui

我正在将 Material-ui 用于 React。

我正在尝试自定义当用户单击 Mui<TextField>组件时转换到位的下划线的颜色,这是 jss 注入以下 CSS 的结果:

.MuiInput-underline:after {
    border-bottom: 2px solid #303f9f;
}
Run Code Online (Sandbox Code Playgroud)

我已经投资于 styled-components 主题提供程序,并且不想引入 MuiTheme 提供程序以使用createMuiThemeoverride

我已经使用 styled-components 来覆盖许多其他 Mui 组件的样式,但无法.MuiInput-underline:after使用 styled-components覆盖。

我现在正在尝试使用 Mui 的 withStyles,但不确定确切的样式语义。我一直没有成功使用 InputProps 和使用类。

const styles = theme => ({
  inputProps: {
    underline: {
      '&:after': {
        border: '2px solid red'
      }
    }
  }
});

const MyTextField = props => {
  const { classes, ...rest } = props;

  return (
    <TextField InputProps={{ inputProps: classes.inputProps }} {...rest} />
  );
};

export default withStyles(styles)(MyTextField);
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?谢谢。

Rya*_*ell 6

以下是如何使用自定义下划线的示例styled-components

import TextField from "@material-ui/core/TextField";
import styled from "styled-components";

const StyledTextField = styled(TextField)`
  /* default */
  .MuiInput-underline:before {
    border-bottom: 2px solid green;
  }
  /* hover (double-ampersand needed for specificity reasons. */
  && .MuiInput-underline:hover:before {
    border-bottom: 2px solid lightblue;
  }
  /* focused */
  .MuiInput-underline:after {
    border-bottom: 2px solid red;
  }
`;

export default StyledTextField;
Run Code Online (Sandbox Code Playgroud)

编辑 TextField 下划线样式组件

相关回答:


Ido*_*Ido 4

您需要省略 styles 对象中的 inputProps 键。
您还需要向 InputProps 提供 Prop 类:

 const styles = theme => ({
    underline: {
      color: 'red' ,
      '&::after': {
        border: '2px solid red'
      }
    }
 });

 const MyTextField = props => {
   const { classes, ...rest } = props;
   return (
     <TextField InputProps={{ classes: {underline: classes.underline} }} {...rest} />
   );
 };
Run Code Online (Sandbox Code Playgroud)

您可以检查此工作代码沙箱示例: https: //codesandbox.io/s/material-demo-75w7p ?fontsize=14