withFormik, pass function as props

爷,独闯天下 提交于 2020-07-09 05:13:45

问题


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);

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?


回答1:


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.

For example:

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/>
}



回答2:


The second argument in the handleSubmit argument set is the formik bag. The props are passed into the formik bag. The props passed into the formik bag can be accessed like so: handleSubmit: (values, { props }) => {...your function here}



来源:https://stackoverflow.com/questions/56727226/withformik-pass-function-as-props

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!