使用withFormik的动态Formik表单

时间:2020-02-20 20:47:38

标签: reactjs forms formik

我正在尝试创建一个React组件,该组件将返回使用withFormik的Formik表单。该组件将通过另一个组件作为道具,该道具返回表单的内容。这可能吗?我无法确定如何将自定义道具传递给mapPropsToValues(基本上是如何将自定义道具放在:

   one:'',
   two:'',
   three:''

在下面的代码中:

const DynamicCustomForm = ({FormType, formName, formFields,  ...props}) => {

    console.log(props);

        const {
            values,
            touched,
            errors,
            status,
            handleChange,
            handleBlur,
            setFieldValue,
            setFieldTouched,
            validateField,
            validateForm,
            handleSubmit,
            isSubmitting,
        } = props;
        return (
            <form onSubmit={handleSubmit}>
                <Field name={formName} >
                    {({
                        field,
                        form,
                        meta,
                    }) => (
                        <FormType />
                    )}
                </Field>

                <Button type="submit" className="button" disabled={isSubmitting}>
                    Submit
                </Button>

            </form>

        );
    };


    const FormikEnhancedDynamicCustomForm = withFormik({
        mapPropsToValues: () => ({
            one:'',
            two:'',
            three:''
        }),
        validateOnMount: false,
        validateOnBlur: false,
        //validate: validate,
        handleSubmit: (values, { setSubmitting }) => {
            handleSubmit(values);
            setTimeout(() => {
                alert(JSON.stringify(values, null, 2));
                setSubmitting(false);
            }, 1000);
        },

        displayName: 'DynamicCustomForm',
    })(DynamicCustomForm);

    export default FormikEnhancedDynamicCustomForm;

1 个答案:

答案 0 :(得分:0)

这篇帖子https://github.com/jaredpalmer/formik/issues/752帮助我确定,如果删除mapPropsToValues,那么我以Formik形式作为道具传递给Component的任何东西都将被添加为Formik值。如果还有其他方法可以达到目的,我仍然会很感兴趣。