问题
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