最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clear Formik field with initial value React - Stack Overflow

programmeradmin4浏览0评论

CodeSandbox:

Question:

Click on reset button and clear a field with value "initial value"


Attempts:

There are too many variants to reset form via:

  1. resetForm()
  2. setFieldValue(<your_field_name>, '')
  3. form.current.reset()

But this list doesn't helpful when you have initial value in formik field.


Snippet:

import React from 'react'
import {Formik, Form, Field} from 'formik'

const Search = () => (
  <Formik onSubmit={({q}, {setSubmitting}) => {
    setSubmitting(false)
  }} initialValues={{q: 'initial value'}} render={({resetForm}) => (
    <Form>
      <Field name='q' />
      <button type="reset" onClick={() => resetForm()}>Reset</button> {/* <== Reset */}
    </Form>
  )}/>
)

CodeSandbox:

https://codesandbox.io/s/kind-fire-q4o45

Question:

Click on reset button and clear a field with value "initial value"


Attempts:

There are too many variants to reset form via:

  1. resetForm()
  2. setFieldValue(<your_field_name>, '')
  3. form.current.reset()

But this list doesn't helpful when you have initial value in formik field.


Snippet:

import React from 'react'
import {Formik, Form, Field} from 'formik'

const Search = () => (
  <Formik onSubmit={({q}, {setSubmitting}) => {
    setSubmitting(false)
  }} initialValues={{q: 'initial value'}} render={({resetForm}) => (
    <Form>
      <Field name='q' />
      <button type="reset" onClick={() => resetForm()}>Reset</button> {/* <== Reset */}
    </Form>
  )}/>
)
Share Improve this question asked Oct 5, 2019 at 16:14 ArthurArthur 3,5167 gold badges35 silver badges65 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

You're totally right - if you have some initial form state, the resetForm action will set the values to those initials. setFieldValue probably the only way to manually clear the field:

<button type="button" onClick={() => setFieldValue('q', '')}>
  Drop field
</button>

notice, type='reset' not need here...

In case when you need to drop multiple fields, take a look at this method: setValues({q: ''})

You can now reset formik by

formik.resetForm({
    values: { name: 'Custom initial values', email: '' },
});

https://formik/docs/migrating-v2#resetform

yes when you reset form values it will reset it to default value you can do the following

<Formik
  enableReinitialize
  onSubmit={(values, { setSubmitting }) => {
    values.q = '';
    setSubmitting(false);
  }}
  initialValues={{ q: "initial value" }}
  render={({ resetForm }) => (
    <Form>
      <Field name="q" />
      <button type="submit">
        Reset form
      </button>{" "}
      {/* <== Reset */}
    </Form>
  )}
/>

Hope it helps

发布评论

评论列表(0)

  1. 暂无评论