how to reset the form and enable submit button after form submision (react-formio)?

浪子不回头ぞ 提交于 2020-01-11 11:59:05

问题


I am using the react-formio package to generate a form dynamically.

I have generated a simple login-form using this link: https://codesandbox.io/s/cra-react-formio-iy8lz

After building, it creates a JSON. Then, I generate a form using that JSON, but when I submit by form after fulfill all validation of form it always is shown in disable mode why?

How can we enable button again ?? when my promise is resolved and how to reset the form after submitting it?

here is my code, codesandbox link

onSubmit={i => {
  alert(JSON.stringify(i.data));
  var promise1 = new Promise(function(resolve, reject) {
     setTimeout(function() {
        resolve("foo");
      }, 300);
   });
 }

one more thing

I also added one more button

{
   label: "Click",
   action: "event",
   showValidations: false,
   block: true,
   key: "click",
   type: "button",
   input: true,
   event: "clickEvent"
},

I also added click handler but it is not working

clickEvent={() => {
  alert("--ss");
}}

回答1:


You can try to use the submission property of the <Form /> component.

As per docs..

Submission data to fill the form. You can either load a previous submission or create a submission with some pre-filled data. If you do not provide a submissions the form will initialize an empty submission using default values from the form.

So in this case you can control the component in a parent component.

Here submissionData is a parent component state and the component initializes with the state from parent (Empty values initially).

<Form submission={{ data: submissionData }} />

Now, inside the onSubmit handler you can try to reset the state and force a re-render.

    onSubmit={() => {
         // Reset submission data
          setSubmissionData({});
        };
      }

Complete code would look like below.

export default () => {
  const [submissionData, setSubmissionData] = useState({});
  return (
    <Form
      //all form props
      submission={{ data: submissionData }}
      onSubmit={() => {
        var promise1 = new Promise(function(resolve, reject) {
          setTimeout(function() {
            resolve("foo");
          }, 300);
        });

        promise1.then(function(value) {
          alert(value);
         // Reset submission data
          setSubmissionData({});
        });
      }}
    />
  }

Attached codesandbox link as comment.



来源:https://stackoverflow.com/questions/58680278/how-to-reset-the-form-and-enable-submit-button-after-form-submision-react-formi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!