我正在使用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] 删除。
我来说两句