【问题标题】: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/coreFormHelperText 组件。

    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】:

        您可以将&lt;TextField/&gt;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>
          );
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-27
          • 2019-06-16
          • 2016-11-13
          • 2019-05-25
          • 1970-01-01
          • 1970-01-01
          • 2023-04-10
          • 2018-06-29
          相关资源
          最近更新 更多