Formik - How to reset form after confirmation

后端 未结 3 1115
时光说笑
时光说笑 2021-02-12 13:42

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.

3条回答
  •  温柔的废话
    2021-02-12 14:22

    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 (
        
          {formProps => {
            return (
              
    ); }}
    ); }

    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 (
        
          {formProps => {
            return (
              
    ); }}
    ); }

    I would still go with the first solution though personally.

提交回复
热议问题