React如何在Material-UI中有条件地覆盖TextField错误颜色?

Marcel Jr.Samson Morasse:

我正在使用React Material-UI库,并且想有条件地覆盖TextField的错误颜色。

当错误属于某种类型时,我需要将helperText,边框,文本和所需的标记颜色更改为黄色。像这样:

在此处输入图片说明

否则,我想为所有其他类型的错误保留默认颜色(红色)。我尝试遵循此codeandbox中使用的相同原理,但无法掌握需要更改的所有组件,因此important几乎每次都必须使用关键字才能看到差异。

我设法有条件地改变了helperText像这样的颜色

                        <TextField
                            label="Name"
                            className={formClasses.textField}
                            margin="normal"
                            variant="outlined"
                            required
                            error={!!errors}
                            helperText={errors && "Incorrect entry."}
                            FormHelperTextProps={{classes: {root: getColorType(AnErrorType)}}}
                        />

getColorType会返回一个CSS对象和属性颜色设置为对应给定的错误类型之一。例如:

hardRequiredHintText: {
    color: `${theme.palette.warning.light} !important`
},

有没有更简单的方法来覆盖MUI错误颜色,并在使用它的所有组件中看到它?

凯凯:

对于每种类型的验证,显示不同的颜色,我们可以将参数传递给makeStyles

import { makeStyles } from "@material-ui/core/styles";
const useStyles = params =>
  makeStyles(theme => ({
    root: {
    }
  }));
const Component = () => {
  const classes = useStyles(someParams)();

在此处输入图片说明


完整代码:

import React from "react";
import "./styles.css";
import { TextField } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = value =>
  makeStyles(theme => ({
    root: {
      "& .Mui-error": {
        color: acquireValidationColor(value)
      },
      "& .MuiFormHelperText-root": {
        color: acquireValidationColor(value)
      }
    }
  }));

const acquireValidationColor = message => {
  switch (message) {
    case "Incorrect entry":
      return "green";
    case "Please input":
      return "orange";
    default:
      return "black";
  }
};

const ValidationTextField = ({ helperText }) => {
  const classes = useStyles(helperText)();
  return (
    <TextField
      label="Name"
      margin="normal"
      variant="outlined"
      required
      error={helperText !== ""}
      helperText={helperText}
      className={classes.root}
    />
  );
};

export default function App() {
  const data = ["Incorrect entry", "Please input", ""];
  return (
    <div className="App">
      {data.map((x, idx) => (
        <ValidationTextField helperText={x} key={idx} />
      ))}
    </div>
  );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章