首页 > 解决方案 > 如何显示自定义在 formik 字段组件中并禁用默认消息

问题描述

我正在使用ReactMaterialFormikformik-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 而不是默认样式,因此我在该字段下方添加了。但是使用这种方法,错误消息会被打印两次。

在此处输入图像描述

如何禁用打印默认消息?

标签: reactjsmaterial-uiformikyupformik-material-ui

解决方案


您可以使用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
>

推荐阅读