我有一个 Material UI TextField 作为输入,我需要强制输入的文本为大写。我尝试过使用
textTransform: "uppercase"
作为样式属性的一部分,但这似乎不起作用。我的组件中的所有其他样式都已正确应用,但 textTransform 却没有。
我还尝试使用标准样式方法将我的样式作为道具传递给组件,但我得到了相同的结果。
我的组件:
const MenuInput = (props) => {
const useStyles = makeStyles((theme) => ({
input: {
textTransform: "uppercase",
marginTop: "10px",
width: "100%",
borderRadius: 4,
backgroundColor: "#FFFFFF",
},
}));
const classes = useStyles();
return (
<TextField
className={classes.input}
id={props.id}
color="primary"
label={props.label}
variant="filled"
onChange={(e) => props.onChange(e)}
error={props.isError}
helperText={props.error}
/>
);
};
输出:
您可以尝试通过
inputProps
应用样式,如下所示:
<TextField
className={classes.input}
id={props.id}
color="primary"
label={props.label}
variant="filled"
onChange={(e) => props.onChange(e)}
error={props.isError}
helperText={props.error}
inputProps={{ style: { textTransform: "uppercase" } }}
/>
我将留下一个带有沙箱的链接,我在其中测试了该解决方案。
尝试添加重要的 textTransform:“大写!重要”
或者添加内联样式
需要注意的是,仅更改样式不会更改发送到 onChange 的实际状态值。这只会显示大写,但保存的数据仍将是原来的小写等。
更改样式不会改变实际值。 您可以在这里检查: https://codesandbox.io/s/textfield-uppercase-material-ui-forked-nhkzpn
如果你想将值变成大写,可以在 onChange 事件中进行:
const MenuInput = (props) => {
const useStyles = makeStyles((theme) => ({
input: {
textTransform: "uppercase",
marginTop: "10px",
width: "100%",
borderRadius: 4,
backgroundColor: "#FFFFFF",
},
}));
const [val, setVal] = useState(props.value);
const handleChange = (e) => {
setVal(e.target.value.toUpperCase());
props.onChange(e)
}
const classes = useStyles();
return (
<TextField
className={classes.input}
id={props.id}
value={val}
color="primary"
label={props.label}
variant="filled"
onChange={handleChange}
error={props.isError}
helperText={props.error}
/>
);
};
或者做得更通用,并将函数传递给 onChange 事件,这样您就可以进行任何转换。您还可以将此函数作为道具传递给您的 MenuItem 组件。
const MenuInput = (props) => {
const useStyles = makeStyles((theme) => ({
input: {
textTransform: "uppercase",
marginTop: "10px",
width: "100%",
borderRadius: 4,
backgroundColor: "#FFFFFF",
},
}));
const [val, setVal] = useState(props.value);
const transormFn = (s) => s.toUpperCase();
const handleChange = (e, fn) => {
if (fn) setVal(fn(e.target.value));
props.onChange(e)
}
const classes = useStyles();
return (
<TextField
className={classes.input}
id={props.id}
value={val}
color="primary"
label={props.label}
variant="filled"
onChange={e => handleChange(e, transformFn)}
error={props.isError}
helperText={props.error}
/>
);
};