【问题标题】:React Material UI OutlinedInput does not display error messageReact Material UI OutlinedInput 不显示错误信息
【发布时间】:2020-06-30 09:00:26
【问题描述】:
我正在使用 React 和 Material UI 来显示一个概述的输入。我可以让它显示 error 道具设置为 true 时出现错误,但是当我尝试添加 helperText 并将我的消息作为道具添加时出现问题:
<OutlinedInput
margin="dense"
value=""
placeholder="my placeholder"
error
helperText="There has been an error" // Property 'helperText' does not exist on type 'IntrinsicAttributes & OutlinedInputProps'
/>
有什么方法可以同时使用OutlinedInput 并显示错误帮助消息?
【问题讨论】:
标签:
javascript
reactjs
typescript
material-ui
【解决方案1】:
您可以使用来自@material-ui/core 的FormHelperText 组件。
const [accountId, setAccountId] = useState({ value: "", error: "" });
<FormControl variant="outlined">
<InputLabel htmlFor="accountId">Account Id</InputLabel>
<OutlinedInput
value={accountId.value}
onChange={(e) => setAccountId({value: e.target.value, error:""})}
inputProps={{
"aria-label": "Account Id",
}}
labelWidth={74}
error={!!accountId.error}
/>
{!!accountId.error && (
<FormHelperText error id="accountId-error">
{accountId.error}
</FormHelperText>
)}
</FormControl>
【解决方案2】:
您正在使用 TextField 在内部使用的基本输入组件。如果您有一些特殊要求,您可以编写自己的文本字段,例如给定的here。
否则使用带有 variant="outlined" 的TextField:
<TextField
margin="dense"
value=""
placeholder="my placeholder"
error
helperText="There has been an error"
variant="outlined"
/>
【解决方案3】:
您可以将<TextField/> 与variant="outlined" 一起使用
这是CSB-Project Link
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
root: {
"& > *": {
margin: theme.spacing(1),
width: "25ch"
}
}
}));
export default function BasicTextFields() {
const classes = useStyles();
return (
<form className={classes.root} noValidate autoComplete="off">
<TextField
id="outlined-basic"
label="Outlined"
variant="outlined"
margin="dense"
value=""
placeholder="my placeholder"
error
helperText="There has been an error"
/>
</form>
);
}