本文介绍了withFormik,传递函数作为道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Formik构建用户输入表单.我正在使用withFormik处理我的表单.我目前正在这样传递我的handleSubmit到我的组件中:

I am using Formik to build an user input Form. And I am using withFormik to handle my Form.I am currently passing my handleSubmit inside my component like this:

export const CreateForm = withFormik({
  mapPropsToValues: () => ({
    primarySkill: "12"
  }),
  validationSchema: () => FormSchema,

  handleSubmit: (values, { setSubmitting }) => {
    setTimeout(() => {
      alert(JSON.stringify(values, null, 2)); // For testing
      setSubmitting(false);
    }, 1000);
  }
})(MyForm);

我希望在App.js(根)组件中传递类似<CreateForm handleSubmit={handleSubmit} />的内容,而不是这样做.有人可以给我一个提示怎么做吗?

Instead of doing this way, I would like to pass something like this <CreateForm handleSubmit={handleSubmit} /> in my App.js (root) component. Can anyone give me a hint how to do it, please?

推荐答案

您可以按照提示底部的方式通过props传递函数.然后,可以将withFormik调用包装在CreateForm组件的函数主体内,以便可以将props传递给CreateForm组件,并让CreateForm控制这些道具如何映射到Formik组件.

You can pass a function via props in the way that you hint at at the bottom of your question. Then you can wrap the withFormik call inside the function body of your CreateForm component so that you can pass props to the CreateForm component and have CreateForm control how those props get mapped to the Formik component.

例如:

const MyComponent = props => {
    function handleSubmit(values, { setSubmitting }) {
        // handle
    }

    return (
        <CreateForm handleSubmit={ handleSubmit }/>
    )
}

const CreateForm = props => {
    const { handleSubmit } = props;

    const MyFormWithFormik = withFormik({
        // ...,
        handleSubmit: handleSubmit,
    })(MyForm);

    return <MyFormWithFormik/>
}

这篇关于withFormik,传递函数作为道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-21 21:56