reactjs - 如何显示自定义在 formik 字段组件中并禁用默认消息
问题描述
我正在使用React、Material、Formik、formik-material-ui制作一个网络项目。
我使用yup制作了一个 Formik 表单进行验证。
const schema = yup.object({
name: yup.string().trim().lowercase().required("Name is required."),
});
<Formik
initialValues={{
name: "",
}}
validationSchema={schema}
>
{({ submitForm, isSubmitting, handleSubmit, handleChange, values }) => (
<Form noValidate onSubmit={handleSubmit}>
<Grid container direction="row" spacing={2}>
<Grid container item xs={12} spacing={4}>
<Grid item xs={4}>
<InputLabel>Patient Name *</InputLabel>
<TextField fullWidth name="name" type="text" />
<InputLabel>Patient ID: P0006</InputLabel>
</Grid>
</Grid>
</Grid>
</Form>
)}
</Formik>
TextField 是一个自定义组件,如下所示
import React, { Fragment } from "react";
import { Field, ErrorMessage } from "formik";
import { TextField } from "libs/formik-material-ui/src";
const TextFieldStyle = {
padding: 8,
fontSize: "0.75rem",
};
export default React.memo((props: any) => {
return (
<Fragment>
<Field
component={TextField}
inputProps={{
style: TextFieldStyle,
}}
size="small"
margin="none"
variant="outlined"
{...props} // add props at the key to override any user defined similar props
>
{props.children}
</Field>
<ErrorMessage name={props.name}>{(msg) => <div style={{ color: "red", textAlign: "left" }}>{msg}</div>}</ErrorMessage>
</Fragment>
);
});
由于我想显示不同样式的 ErrorMessage 而不是默认样式,因此我在该字段下方添加了。但是使用这种方法,错误消息会被打印两次。
如何禁用打印默认消息?
解决方案
您可以使用helperText=""
禁用默认消息
<Field
component={TextField}
inputProps={{
style: TextFieldStyle,
}}
size="small"
margin="none"
variant="outlined"
helperText=""
{...props} // add props at the key to override any user defined similar props
>
推荐阅读
- c# - Linq Count() 超时 - 执行超时已过期。操作完成前超时时间已过或服务器无响应
- r - 删除组中在 R 中第一次出现多个因子变量水平之后的所有行
- shell - Jenkins 文件中用于 SQL 查询的错误处理
- sql - 在 SQLite 中比较和获取记录时出错
- javascript - 如何从包含所有页面的 JS 代码的单个 JS 文件中使用特定于某些页面的 JS 代码?
- android - 如何将 multi_image_picker2 `Asset` 转换为 `File` 对象?
- python - Python MongoDB更新索引处的数组元素
- react-native - 在 linux 中使用 npx react-native init AwesomeProjectError 时出错
- discord - 删除特定频道 discord.js v.13
- c++ - 在 Visual Studio 2019 上编译 LLVM 时出现 libomp 错误