首页 > 解决方案 > 是的验证,helperText 添加到 MaterialUI 输入组件

问题描述

我正在使用材质 UI 来接受文件类型和上传文件,我正在尝试将 Yup 验证与此集成,但是 Input 不允许在其定义中使用 helperText,它确实允许在取消时报告红色下划线的错误在上传之后,如何将 helperText 值添加到我的输入中并收到错误消息?

<FormControl className={classes.margin}>
                      <Input
                        className={classes.fileUpload}
                        type="file"
                        id="file"
                        onChange={onSelectFile}
                        name="file"
                        inputProps={fileRestrict}
                        error={touched.file && Boolean(errors.file)}
                        helperText={touched.file ? errors.file : ''}
                      />
                    </FormControl>

上面的 helperText 永远不会真正呈现在 UI 上的输入组件下方,我应该在其中包装输入以使其工作吗?

  file: Yup.mixed('Please Select a file').when('isEdit', {
    is: false,
    then: Yup.mixed().required(
      'File is required if you are uploading a document'
    ),
  }),

我通过道具传入的validationSchema

标签: javascriptreactjsyup

解决方案


来自材料 UI TextField 文档 - https://material-ui.com/api/text-field/

高级配置:了解文本字段是以下组件之上的简单抽象很重要:FormControl, InputLabel, FilledInput, OutlinedInput, Input,FormHelperText

您正在尝试使用该FormHelperText组件,但是您正在使用Input不包含该组件的FormHelperText组件作为子组件。您可以单独使用一个FormHelperText组件作为同级组件,也可以使用一个TextField组件并相应地对其进行配置。许多相同的道具被传递给Input组件。InputProps但是,您可以使用 的属性直接传递的任何其他内容TextField(注意这是区分大小写"i"的,小写字母会影响 HTML 输入元素,大写字母"I"会影响 Material UIInput组件)

<TextField 
  className={classes.margin}
  type="file"
  error={touched.file && Boolean(errors.file)}
  helperText={touched.file ? errors.file : ''}
  onChange={onSelectFile}
  InputProps={{className: classes.fileUpload}}
  inputProps={{id: "file"}}
/>

推荐阅读