我有一个通过道具接收一组颜色的对话框。根据这组颜色,我需要为我的 Material UI TextField 设置边框颜色,但我无法让它工作。
我有这个makeStyles:
const useStyles = makeStyles(theme => ({
root: {
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: ({colors}) => `${colors ? colors.greenAccent[600] : "white"}`,
},
},
},
})
);
这是我的文本字段
<TextField
style={{ marginLeft: "4px", marginTop: "8px", color: colors ? colors.grey[200] : "white"}}
className={classes.root}
label="Valor da meta"
variant="outlined"
name="valor_meta"
id="valor_meta"
InputLabelProps={{
style: {
color: colors ? colors.grey[200] : "white",
}
}}
value={valorMeta}
onChange={(e) => {
const inputValue = e.target.value;
if (/^[0-9.,]*$/.test(inputValue)) {
if (
inputValue.indexOf(".") === inputValue.lastIndexOf(".") &&
inputValue.indexOf(",") === inputValue.lastIndexOf(",")
) {
if (
!(inputValue.includes(",") && inputValue.includes("."))
) {
setValorMeta(inputValue);
}
}
}
}}
/>
当我打开对话框时,边框颜色在聚焦时保持默认颜色,但如果我保存对话框文件,正确的颜色将应用于边框。我怎样才能让它工作而不出现这个保存问题?
我认为makeStyles允许使用接收props的函数来自定义样式,当我们在函数式组件中时,创建样式的hook方式makeStyles并不能直接访问组件的props,就像这样不是基于组件的方法。
使用 withStyles 方法代替 makeStyles:
import { TextField, withStyles } from '@material-ui/core';
const CustomTextField = withStyles(theme => ({
root: {
'& label.Mui-focused': {
color: props => props.colors ? props.colors.grey[200] : "white",
},
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: props => props.colors ? props.colors.greenAccent[600] : "white",
}
},
},
}))(TextField);
export default function MyComponent({colors}) {
// ...
return (
<CustomTextField
// other props
colors={colors}
/>
);
}
上面,我们定义了一个新的 CustomTextField 组件,它是通过将 withStyles 中的样式应用到标准 TextField 组件来创建的。
样式的定义与您最初的定义几乎相同,但现在它位于 withStyles 而不是 makeStyles 中,并且它直接从组件获取道具。
现在您可以使用 CustomTextField 作为组件中 TextField 的直接替代品。然后,此 CustomTextField 将能够接收颜色属性并应用于样式。您可以将颜色道具直接传递给 CustomTextField。