reactjs - 基于服务器端验证向文本字段添加图标(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。请帮忙!
解决方案
有同样的问题:
我修复它的步骤:
将我的 Formik {Field} 模块添加到 Material UI {Textfield} 模块中,以便能够使用 InputProps={} 添加图标。这也需要读取 {handleChange, handleBlur} 道具,否则验证不会在字段中启动。
我使用 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
变为绿色勾号。
推荐阅读
- jboss - Wildfly 13 ejb 无状态会话 bean 未从池中删除
- python - 关于 Anaconda 的 python 和原生 macOS python
- dart - 如何在 Dart 中检查和转换泛型参数?
- arm - 理解这行乘以 8 的 VHDL 代码
- asp.net-core - 添加对程序集 .net 核心的引用
- wordpress - 在 woocommerce 中搜索和过滤产品
- apache-beam - Java ParquetIO 可以写空的 parquet 文件吗?如何?
- ios - popToRootViewController 未按预期工作
- javascript - 溢出:滚动;属性没有提供足够的滚动深度
- javascript - 在 html/css/javascript 中使用 for 循环创建 element_id-value