我如何设置React Material-UI必需的TextField的样式

时间:2019-04-24 23:11:54

标签: reactjs material-ui

documentation说,您可以将自定义CSS添加到TextField。

例如单击它时,第二个TextField变为紫色:

  <TextField
    className={classes.margin}
    InputLabelProps={{
      classes: {
        root: classes.cssLabel,
        focused: classes.cssFocused,
      },
    }}
    InputProps={{
      classes: {
        root: classes.cssOutlinedInput,
        focused: classes.cssFocused,
        notchedOutline: classes.notchedOutline,
      },
    }}
    label="Custom CSS"
    variant="outlined"
    id="custom-css-outlined-input"
  />

我如何使我的必需文本字段始终具有突出显示(在聚焦之前),类似于错误文本字段的显示方式?

我可以将星号设置为橙色,但似乎无法更改线条的颜色:

const styles = theme => ({
  labelAsterisk: {
    color: "orange"
  }
});

    <TextField
      id="name"
      label="Name"
      required
      InputLabelProps={{
        FormLabelClasses: {
          asterisk: classes.labelAsterisk
        }
      }}
      margin="normal"
    />

编辑:如果使用概述 TextField,则可以更改颜色。但是,我想为普通的TextField做到这一点。

const styles = theme => ({
  greenOutline: {
    borderColor: "green !important"
  }
});

    <TextField
      id="custom-css-outlined-input"
      label="Custom CSS"
      variant="outlined"
      InputProps={{
        classes: {
          notchedOutline: classes.greenOutline
        }
      }}
    />

1 个答案:

答案 0 :(得分:0)

有关有效的示例,请参见https://codesandbox.io/s/5yyo503794

关键部分是:

underline中的InputProps

      InputProps={{
        classes: {
          underline: classes.cssRequired
        }
      }}

关联的CSS中的&:before类和borderBottom样式

  cssRequired: {
    "&:before": {
      borderBottom: "2px solid orange"
    }
  },

较大的代码段:

const styles = theme => ({
  labelAsterisk: {
    color: "red"
  },
  cssLabel: {
    color: "orange"
  },
  cssRequired: {
    "&:before": {
      borderBottom: "2px solid orange"
    }
  },
});


    <TextField
      id="requiredField"
      label="Required Field"
      value="Custom Text"
      required
      InputLabelProps={{
        classes: {
          root: classes.cssLabel
        },
        FormLabelClasses: {
          asterisk: classes.labelAsterisk
        }
      }}
      InputProps={{
        classes: {
          underline: classes.cssRequired
        }
      }}
      margin="normal"
    />