首页 > 解决方案 > 基于服务器端验证向文本字段添加图标(Formik+Yup+Material UI)

问题描述

我正在尝试根据 api 响应在文本字段中显示一个勾号或十字图标。

我的文本字段看起来像这样。我添加了 inputProps 并添加了一个装饰。但我想根据一个函数显示不同的图标,如果它有效或无效,它将返回。

          <TextField
            error={errors.username && touched.username}
            variant="outlined"
            required
            fullWidth
            name="username"
            label="Username"
            onChange={handleChange}
            helperText={touched.username && errors.username}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end" disablePointerEvents="true">
                  <CheckCircleOutlineIcon
                    style={{ color: green[500] }}
                    fontSize="small"
                  ></CheckCircleOutlineIcon>
                </InputAdornment>
              ),
            }}
          />

但这一直显示,在 handleChange 事件中,我想触发一个函数,让我决定要显示哪个图标。我尝试了很多谷歌搜索,但它没有帮助。我看到这可以像我展示的图像一样在 mdBootstrap 中轻松实现,但我使用材料 ui 和 yup 进行验证和 formik。请帮忙! 在此处输入图像描述

标签: reactjsmaterial-uireact-hooksformikyup

解决方案


有同样的问题:

我修复它的步骤:

  1. 将我的 Formik {Field} 模块添加到 Material UI {Textfield} 模块中,以便能够使用 InputProps={} 添加图标。这也需要读取 {handleChange, handleBlur} 道具,否则验证不会在字段中启动。

  2. 我使用 endAdorment 属性将图标添加到字段中,并直接在其中添加条件以根据 Formik 验证显示正确的图标。

我没有通过 API 调用验证对其进行检查,但我认为它与它的工作方式类似。

<Field
            component={TextField}
            error={errors.username && touched.username && true}
            variant="outlined"
            required
            fullWidth
            name="username"
            label="Username"
            onChange={handleChange}
            onBlur={handleBlur}
            helperText={touched.username && errors.username}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end" disablePointerEvents="true">
                  {errors.username && touched.username && (
                    <CancelIcon
                      style={{ color: "red" }}
                      fontSize="default"
                    ></CancelIcon>
                  )}
                  {!errors.username && touched.username && (
                    <CheckCircleIcon
                      style={{ color: "#05cc30" }}
                      fontSize="default"
                    ></CheckCircleIcon>
                  )}                  
                </InputAdornment>
              ),
            }}
          />

我直接在 endAdornment 中添加了条件,它检查errors.username 是否被触摸并显示 Cross 或如果被触摸并!errors.username 变为绿色勾号。


推荐阅读