简体   繁体   中英

React multiple forms with single submit handler

I have a common event handler for form submit

handleSubmit = (e) => {
    e.preventDefault();
    const errors = this.validate();
    this.setState({ errors: errors || {} });
    if (errors) return;
    this.doSubmit();
  };

It will handle validation and call another function doSubmit(); If I have 3 different forms, all forms calls doSumbit();

How to make different submission call based on the related form... also how to handle related form field validation...

As I understood. You have to give each form an id. And then you can use this.

if(e.target.id==='formid1'){
      console.log('formid1');
}
else if(....

** you can use for="id of your form" in your button **

 <form id="myForm" method="post">
        <input type="text" id="username" name="username" required>
        <center><button for="myForm" type="submit">Continue</button> </center>
        </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM