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

IT技术 javascript html css reactjs material-ui
2021-05-04 14:46:19

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

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

在此处输入图片说明

否则,我想为所有其他类型的错误保留默认颜色(红色)。我试图遵循在这个代码和盒子中使用的相同原则,但我无法掌握需要更改的所有组件,而且我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 错误颜色并查看它反映在所有使用它的组件中?

3个回答

对于每种类型的验证,显示不同的颜色,我们可以将参数传递给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>
  );
}

输出对于基于类的组件

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

const commonStyles = (theme) =>
  createStyles({
    root: {},

    warningStyles: {
      "& .MuiFormLabel-root.Mui-error": {
        color: "orange !important"
      },
      "& .MuiInput-underline.Mui-error:after": {
        borderBottomColor: "orange !important"
      },
      "& .MuiFormHelperText-root.Mui-error": {
        color: "orange !important"
      }
    }
  });

class DemoComponent extends React.Component {
  render() {
    const { classes } = this.props;
    const _text1HasWarning = false;
    const _text2HasWarning = true;
    const _text3HasWarning = false;

    return (
      <>
        <TextField
          error={false}
          className={_text1HasWarning ? classes.warningStyles : null}
          value="Valid Value"
          variant="standard"
          label="Valid label"
          helperText="Valid helper text"
        />
        <br />
        <br />
        <br />
        <TextField
          error={true}
          className={_text2HasWarning ? classes.warningStyles : null}
          value="warning value"
          variant="standard"
          label="warning label"
          helperText="warning helper text"
        />
        <br />
        <br />
        <br />
        <TextField
          error={true}
          className={_text3HasWarning ? classes.warningStyles : null}
          value="error value"
          variant="standard"
          helperText="error helper text"
          label="error label"
        />
      </>
    );
  }
}
export default withStyles(commonStyles)(DemoComponent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

输出

您可以通过覆盖 Material-UI 主题默认样式然后将文本字段或组件包装在 myTheme 中来实现此目的

import { createMuiTheme } from 'material-ui/styles';
 const myTheme = createMuiTheme({
 overrides:{
    MuiInput: {
        underline: {
                '&:after': {
                  backgroundColor: 'any_color_value_in_hex',
                }
             },
          },
       }
   });
   export default myTheme;

然后将其导入您的组件并使用:

import {MuiThemeProvider} from 'material-ui/styles';
import myTheme from './components/myTheme'

<MuiThemeProvider theme = {myTheme}>
  <TextField />
</MuiThemeProvider>

我希望它能帮助你。