簡體   English   中英

如何使用渲染道具和設計庫作為輸入,在 formik 中正確使用 Formik ErrorMessage?

[英]How to use Formik ErrorMessage properly with formik using render props and design library for inputs?

我想觸發 formik 錯誤並在單擊輸入且值不正確時進行觸摸。 我將 formik props 傳遞給輸入組件,如下所示:

const initialValues = {
    title: ''
};

const validationSchema = yup.object({
    title: yup.string().max(50, 'less than 50 words !!').required('required !!')
});

function Add() {
        <Formik initialValues={initialValues} onSubmit={onSubmit} validationSchema={validationSchema}>
            {(props) => {
                return (
                    <Form>
                                    <AddTitle props={props} />
                    </Form>
                );
            }}
        </Formik>
    );
}

在這里,我試圖在觸摸輸入時顯示錯誤消息,並且出現這樣的錯誤:

import { Input } from 'antd';

function AddTitle(props) {
    console.log(props.props);
    return (
            <Field name="title">
                {() => {
                    return (
                        <Input
                            onChange={(e) => {
                                props.props.setFieldValue('title', e.target.value)
                            }}
                        />
                    );
                }}
            </Field>
            <ErrorMessage name="title" />
            <P>
                {props.props.touched.title && props.props.errors.title && props.props.errors.title}
            </P>
        </React.Fragment>
    );
}

但是 ErrorMessage 和它下面的段落在輸入被觸摸和為空時不起作用。

在控制台日志中,它顯示輸入不處理 formik 觸摸方法,它只會觸發它的錯誤:

touched:
__proto__: Object
errors:
title: "less than 50 words !"
__proto__: Object

在將 formik props 傳遞給組件並使用第三個庫進行輸入時,如何正確使用 ErrorMessage ?

通過向輸入添加 onBlur 解決了該問題,並且 ErrorMessage 工作正常:

<Field name="title">
                {() => {
                    return (
                        <Input
                            onBlur={() => props.props.setFieldTouched('title')}
                            onChange={(e) => {
                                props.props.setFieldValue('title', e.target.value);
                            }}
                        />
                    );
                }}
            </Field>
            <P class="mt-2 text-danger">
                <ErrorMessage name="title" />
            </P>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM