简体   繁体   English

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

[英]React How to conditionally override TextField error color in Material-UI?

I'm using React Material-UI library and I want to conditionally override the error color of a TextField.我正在使用React Material-UI库,我想有条件地覆盖 TextField 的错误颜色。

I need to change the helperText, border, text and required marker color to yellow when the error is of a certain type.当错误属于某种类型时,我需要将 helperText、边框、文本和所需的标记颜色更改为黄色。 Something like that:像这样的东西:

在此处输入图像描述

Otherwise, I want to keep the default color(red) for every other type of error.否则,我想为所有其他类型的错误保留默认颜色(红色)。 I tried to follow the same principle used in this codesandbox but I couldn't get a grip of all the components that I needed to change and I had to use the important keyword almost every time to see a difference.我尝试遵循此代码盒中使用的相同原则,但我无法掌握需要更改的所有组件,并且几乎每次都必须使用important关键字才能看到差异。

I have managed to conditionally change the color of the helperText like so:我设法有条件地改变了helperText的颜色,如下所示:

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

The getColorType will return a CSS object with the property color set to the one that corresponds the given error type. getColorType将返回 CSS object 属性颜色设置为与给定错误类型对应的颜色。 ex:前任:

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

Is there an easier way to override MUI error color and to see it reflected in all the component that uses it?有没有更简单的方法来覆盖 MUI 错误颜色并看到它反映在所有使用它的组件中?

For each type of validation, display a different color, we can pass params to makeStyles对于每种类型的验证,显示不同的颜色,我们可以将参数传递给makeStyles

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

在此处输入图像描述


Full code:完整代码:

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>
  );
}

输出 For Class Based Components对于基于 Class 的组件

 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>

Output Output

You can accomplish this by overriding your Material-UI theme default styles and then wrapping your text field or your component inside of myTheme您可以通过覆盖 Material-UI 主题默认 styles 然后将文本字段或组件包装在 myTheme 中来完成此操作

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

and then import it into your component and use:然后将其导入您的组件并使用:

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

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

I hope it helps you.我希望它对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM