简体   繁体   English

如何使用 antd 和 formik 设置和获取日期选择器值?

[英]How to set and get a datepicker value using antd with formik?

Here i am creating Datepicker with antd and passing this antd datepicker to formik field.My sample code for Datepicker with antd在这里,我使用 antd 创建 Datepicker 并将这个 antd datepicker 传递给 formik 字段。我使用 antd 的 Datepicker 示例代码

    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

i am adding this ant component to formik field component,submit the form using handleSubmit and applying the YUP validations.我正在将此 ant 组件添加到 formik 字段组件中,使用 handleSubmit 提交表单并应用 YUP 验证。 iam getting a problem was submitting the form iam getting the required validation of DatePicker, and problem is selecting the values of DatePicker iam not getting the value and validation message is displayed after submitting the form.我在提交表单时遇到问题,我正在获取所需的 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>  
 )
   }

}

Here i am getting the values through withFormik and submitting the form using handleSubmit.在这里,我通过 withFormik 获取值并使用 handleSubmit 提交表单。 Why iam not getting datepicker value and why validation message is displayed after selecting a datepicker value?为什么我没有获得 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)

In your DateInput component try to set value with setFieldValue() method of Formik whether it is valid or not.在您的DateInput组件中,尝试使用 Formik 的setFieldValue()方法设置值,无论它是否有效。 I believe you can extract it from via: form: { touched, errors, setFieldValue } .我相信您可以通过以下form: { touched, errors, setFieldValue }提取它: form: { touched, errors, setFieldValue }

Also check touched items in your form, and make sure that you are changing the value of your date field.还要检查表单中的touched项目,并确保您正在更改日期字段的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM