【发布时间】:2021-11-06 00:54:53
【问题描述】:
我正在使用React、Material、Formik、formik-material-ui 制作一个 Web 项目。
我已经使用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 而不是默认样式,因此我在字段下方添加了。 但是使用这种方法,错误消息会被打印两次。
如何禁用打印默认消息?
【问题讨论】:
-
请查看文档link
标签: reactjs material-ui formik yup formik-material-ui