Formik-确认后如何重设表格 [英] Formik - How to reset form after confirmation

查看:377
本文介绍了Formik-确认后如何重设表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Formik 中,如何使重置"按钮仅在确认后重置表单?

In Formik, how to make the Reset button reset the form only after confirmation?

即使您单击取消",下面的我的代码仍会重置表单.

My code below still resets the form even when you click Cancel.

var handleReset = (values, formProps) => {
    return window.confirm('Reset?'); // still resets after you Cancel :(
};

return (
  <Formik onReset={handleReset}>
    {(formProps) => { 
      return (
        <Form>
          ...
          <button type='reset'>Reset</button>
        </Form>
      )}}
  </Formik>
);

推荐答案

我不确定,但是我认为您必须编写自己的reset函数,而无需使用reset类型的按钮.像这样:

I'm not completely certain, but I think you will have to write your own reset function without a button with a reset type. Something like this:

const handleReset = (resetForm) => {
  if (window.confirm('Reset?')) {
    resetForm();
  }
};

function Example() {
  return (
    <Formik initialValues={{ value: 1 }}>
      {formProps => {
        return (
          <Form>
            <Field name="value" type="number" />
            <button
              onClick={handleReset.bind(null, formProps.resetForm)}
              type="button"
            >
              Reset
            </button>
          </Form>
        );
      }}
    </Formik>
  );
}

如果您真的想使用onReset,我认为唯一的方法是抛出错误. Formik 源代码似乎表明resetForm()将不管您的onReset()函数返回什么,都将被调用.

If you really want to use onReset, I think the only way is to throw an error. The Formik source code seems to indicate resetForm() will be called no matter what your onReset() function returns.

const handleReset = () => {
  if (!window.confirm('Reset?')) {
    throw new Error('Cancel reset');
  }
};

function Example() {
  return (
    <Formik initialValues={{ value: 1 }} onReset={handleReset}>
      {formProps => {
        return (
          <Form>
            <Field name="value" type="number" />
            <button type="reset">
              Reset
            </button>
          </Form>
        );
      }}
    </Formik>
  );
}

尽管我个人还是会采用第一个解决方案.

I would still go with the first solution though personally.

这篇关于Formik-确认后如何重设表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆