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

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

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

https://img1.sycdn.imooc.com/653fa4230001f7b502490101.jpg

否则,我想为所有其他类型的错误保留默认颜色(红色)。我尝试遵循此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 对象,其属性 color 设置为与给定错误类型相对应的颜色。前任:


hardRequiredHintText: {

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

},

是否有更简单的方法来覆盖 MUI 错误颜色并查看它反映在所有使用它的组件中?


ABOUTYOU
浏览 114回答 1
1回答

互换的青春

对于每种类型的验证,显示不同的颜色,我们可以将参数传递给makeStylesimport { makeStyles } from "@material-ui/core/styles";const useStyles = params =>&nbsp; makeStyles(theme => ({&nbsp; &nbsp; root: {&nbsp; &nbsp; }&nbsp; }));const Component = () => {&nbsp; 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 =>&nbsp; makeStyles(theme => ({&nbsp; &nbsp; root: {&nbsp; &nbsp; &nbsp; "& .Mui-error": {&nbsp; &nbsp; &nbsp; &nbsp; color: acquireValidationColor(value)&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; "& .MuiFormHelperText-root": {&nbsp; &nbsp; &nbsp; &nbsp; color: acquireValidationColor(value)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }));const acquireValidationColor = message => {&nbsp; switch (message) {&nbsp; &nbsp; case "Incorrect entry":&nbsp; &nbsp; &nbsp; return "green";&nbsp; &nbsp; case "Please input":&nbsp; &nbsp; &nbsp; return "orange";&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; return "black";&nbsp; }};const ValidationTextField = ({ helperText }) => {&nbsp; const classes = useStyles(helperText)();&nbsp; return (&nbsp; &nbsp; <TextField&nbsp; &nbsp; &nbsp; label="Name"&nbsp; &nbsp; &nbsp; margin="normal"&nbsp; &nbsp; &nbsp; variant="outlined"&nbsp; &nbsp; &nbsp; required&nbsp; &nbsp; &nbsp; error={helperText !== ""}&nbsp; &nbsp; &nbsp; helperText={helperText}&nbsp; &nbsp; &nbsp; className={classes.root}&nbsp; &nbsp; />&nbsp; );};export default function App() {&nbsp; const data = ["Incorrect entry", "Please input", ""];&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; {data.map((x, idx) => (&nbsp; &nbsp; &nbsp; &nbsp; <ValidationTextField helperText={x} key={idx} />&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </div>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5