乐闻世界logo
搜索文章和话题

Formik - How to reset form after confirmation

1个答案

1

Formik is a popular React library for handling form state management and validation. To reset a form in Formik, you can use the resetForm function from Formik. resetForm is one of the helper methods for Formik forms, typically available within the Formik component or the useFormik hook.

Here are several scenarios for using the resetForm method to reset a form:

Using the Formik Component

If you are using the Formik component, you can access the resetForm method within the render prop or the children function via Formik's rendering properties.

jsx
import { Formik, Form, Field } from 'formik'; const MyForm = () => ( <Formik initialValues={{ name: '' }} onSubmit={(values, actions) => { // Submission logic actions.resetForm(); }} > {({ resetForm }) => ( <Form> <Field name="name" type="text" /> <button type="button" onClick={() => resetForm()}> Reset Form </button> <button type="submit">Submit</button> </Form> )} </Formik> );

Using the useFormik Hook

If you are using the useFormik hook, you can directly access the resetForm method from the returned Formik instance.

jsx
import React from 'react'; import { useFormik } from 'formik'; const MyForm = () => { const formik = useFormik({ initialValues: { name: '' }, onSubmit: values => { // Submission logic formik.resetForm(); }, }); return ( <form onSubmit={formik.handleSubmit}> <input name="name" type="text" onChange={formik.handleChange} value={formik.values.name} /> <button type="button" onClick={() => formik.resetForm()}> Reset Form </button> <button type="submit">Submit</button> </form> ); };

Resetting to Specific Values

The resetForm method also accepts an optional parameter. If you want to reset the form to specific values instead of the initial values, you can do the following:

jsx
resetForm({ values: { name: 'Specific Value' } });

With this approach, when you trigger the resetForm method, the form's values will be reset to the provided values.

The above code assumes you have already installed and imported the Formik-related modules, and set up appropriate initial form values and submission handling logic. In actual development, please adjust the logic based on specific requirements.

2024年6月29日 12:07 回复

你的答案