【问题标题】:How to change Material-UI TextField bottom and label color on error and on focus如何在错误和焦点上更改 Material-UI TextField 底部和标签颜色
【发布时间】:2019-05-31 19:51:25
【问题描述】:

我有一个 Material UI TextField 组件需要一些颜色自定义:

  • error
  • focused

我正在使用@material-ui/core 3.8.1 它是<TextField /> 组件。

我想避免使用<MuiThemeProvider>

这就是我根据这里对 Material-UI <Input /> 组件的建议和答案 here 进行尝试的方法

转载:https://codesandbox.io/s/q9yj0y74z6

【问题讨论】:

  • 你可以使用 overriding with classes 方法,看看'<Input/>' component implementation,错误的底线颜色似乎是underline: {'&amp;$error:after': {...}}。对于标签,您需要覆盖InputLabelProps: {{classes: ....}}
  • 对于&amp;$error:after,这已经是我的复制品了。对于InputLabelProps,我尝试了很多组合,包括classes,都没有奏效。
  • '&amp;$error:after' 需要添加到InputProps: {{classes: ....}}
  • 这已经是我的复制品了=/

标签: javascript reactjs ecmascript-6 material-ui


【解决方案1】:

如 cmets 中所述,您需要覆盖 classes 属性。

&amp;$ 语法指的是同一样式表中的类。 您的示例即将完成,但您需要传入一个错误类。

const styles = muiTheme => ({
  label: {
    "&$focusedLabel": {
      color: "cyan"
    },
    "&$erroredLabel": {
      color: "orange"
    }
  },
  focusedLabel: {},
  erroredLabel: {},
  underline: {
    "&$error:after": {
      borderBottomColor: "orange"
    },
    "&:after": {
      borderBottom: `2px solid cyan`
    }
  },
  error: {}
});

<TextFieldMui
      InputLabelProps={{
        classes: {
          root: classes.label,
          focused: classes.focusedLabel,
          error: classes.erroredLabel
        },
      }}
      InputProps={{
        classes: {
          root: classes.underline,
          error: classes.error
        }
      }}
      {...props}
    />

https://codesandbox.io/s/9z70kz5vnr

【讨论】:

【解决方案2】:

用于禁用标签和输入文本颜色更改示例。

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles((theme) => ({
  container: {
    display: "flex",
    flexWrap: "wrap"
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1)
  },
  label: {
    "&$disabled": {
      color: "black"
    }
  },
  inputRoot: {
    "&$disabled": {
      color: "red"
    }
  },
  disabled: {}
}));

export default function OutlinedTextFields() {
  const classes = useStyles();

  return (
    <form className={classes.container} noValidate autoComplete="off">
      <TextField
        disabled
        id="outlined-disabled"
        label="Disabled"
        defaultValue="Hello World"
        InputProps={{
          classes: {
            root: classes.inputRoot,
            disabled: classes.disabled
          }
        }}
        InputLabelProps={{
          classes: {
            root: classes.label,
            disabled: classes.disabled
          }
        }}
        margin="normal"
        variant="outlined"
      />
    </form>
  );
}

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 2019-11-07
    • 1970-01-01
    • 2021-06-29
    • 2018-09-13
    • 2021-12-07
    • 2019-05-31
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多