【问题标题】:React How to conditionally override TextField error color in Material-UI?React 如何有条件地覆盖 Material-UI 中的 TextField 错误颜色?
【发布时间】:2020-07-15 21:03:58
【问题描述】:

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

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

否则,我想为所有其他类型的错误保留默认颜色(红色)。 我尝试遵循codesandbox 中使用的相同原则,但我无法掌握需要更改的所有组件,我几乎每次都必须使用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 错误颜色并在所有使用它的组件中看到它的反映?

【问题讨论】:

标签: javascript html css reactjs material-ui


【解决方案1】:

For 基于类的组件

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 谢谢!这正是我所需要的。我还需要更改边框颜色: "& .MuiOutlinedInput-root.Mui-error": { "& fieldset": { borderColor: acquireValidationColor(value), }, },
    【解决方案3】:

    您可以通过覆盖您的 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>
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2020-08-07
      • 2018-10-26
      • 2019-02-10
      • 2021-12-07
      • 2021-03-21
      • 2018-11-22
      相关资源
      最近更新 更多