Как установить и получить значение datepicker, используя antd с formik? - PullRequest
0 голосов
/ 28 февраля 2019

Здесь я создаю Datepicker с помощью antd и передаю этот antd datepicker в поле formik. Мой пример кода для Datepicker с antd

    import React from "react";
    import { Form, DatePicker } from "antd"
    import { Field } from "formik";
    import moment from 'moment';

    const FormItem = Form.Item;

    function onChange(date, dateString) {
        console.log(date, dateString);

    }
     const dateFormat = "MM-DD-YYYY"

   // Here i am adding antd error message through DateInput

     const DateInput = ({
            field,
            form: { touched, errors },
            ...props
        }) => {
            const errorMsg = touched[field.name] && errors[field.name]
            const validateStatus = errorMsg ? "error"
                : (touched[field.name] && !errors[field.name]) ? "success"
                    : undefined

            return (
                <div>
                    <FormItem 
                    label={props.label}
                    help={errorMsg}
                    validateStatus={validateStatus}
                    hasFeedback
                   {...props.formitemlayout}>

                    <DatePicker onChange={onChange} defaultPickerValue={moment()}/> 
                    </FormItem>

                </div>
            )
        }
        export default DateInput

Я добавляю этот компонент ant в компонент поля formik, отправьте форму, используяhandleSubmit и применение проверок YUP.У меня возникла проблема с отправкой формы. У меня получена необходимая проверка DatePicker, а проблема заключается в выборе значений DatePicker. У меня нет получения значения, и после отправки формы отображается сообщение о подтверждении.

  class FormikApollo extends React.Component {

        render() {
            const { values, handleSubmit, setFieldValue } = this.props
            return (
                <div align="center">
                    <Form onSubmit={handleSubmit}>
                                <Field
                                    name="username"
                                    label="Name"
                                    placeholder="Enter a Name"
                                    component={TextField}
                                    value={values.username}
                                    formitemlayout={formItemLayout}

                                />
                                <Field
                                    name="email"
                                    label="Email"
                                    placeholder="Enter an Email"
                                    component={TextField}
                                    value={values.email}
                                    formitemlayout={formItemLayout}


                                />

                                <Field
                                    name="password"
                                    label="Password"
                                    type="password"
                                    placeholder="Enter a Password"
                                    component={TextField}
                                    formitemlayout={formItemLayout}
                                />
                                 <Field
                                    name="dateofbirth"
                                    label="dateOfBirth"
                                    type="date"
                                    component={DateInput}
                                    formitemlayout={formItemLayout}
                                    defaultValue={values.dateofbirth}
                                    format={dateFormat} 

                                />


                    <Button type="primary" htmlType="submit">Submit</Button>
                     </Form>  
 )
   }

}

Здесь яЯ получаю значения через withFormik и отправляю форму с помощью handleSubmit.Почему я не получаю значение datepicker и почему после выбора значения datepicker отображается сообщение проверки?

 const FormikApp = (withFormik)({
        mapPropsToValues({ username, email, password, dateofbirth }) {
            return {
                username: username || '',
                email: email || '',
                password: password || '',
                dateofbirth: dateofbirth || ''


            }
        },
        validationSchema: Yup.object().shape({
            username: Yup.string()
                .min(3, "Username must be above 3 characters")
                .required("Username is required"),
            email: Yup.string()
                .email("Invalid Email !!")
                .required("Email is required"),
            password: Yup.string()
                .min(6, "Password must be above 6 characters")
                .required("Password is required"),

            dateofbirth: Yup.string().required("Date is required")



        }),
        handleSubmit(values, { resetForm }) {
            resetForm();
            console.log(values)

        }

    })(FormikApollo)

1 Ответ

0 голосов
/ 28 февраля 2019

В вашем DateInput компоненте попытайтесь установить значение с помощью setFieldValue() метода Formik, является ли оно действительным или нет.Я полагаю, что вы можете извлечь его из:

...