简体   繁体   中英

How to create several submit buttons in a react.js form?

I am trying to create a form in react.js where the user can click on two different button to execute two different actions. In my case, the form should allow the user to select a document and either replace the current document (1st button) or to be appended to it (2nd button). Is it possible to achieve this in a single form ?

I thought i could detect which button was applied using the 'event' parameter in the onSubmit function, but didn't success at it. I also thought about recreating a pseudo-form using references to inputs and normal buttons, but I would prefer not to use such a hack if a cleaner solution exists.

Thank you in advance for your help!

Note: I have found some questions related to multiple submit buttons ( here and here for example), but none of them deal with react.js solutions.

Try this. It will process a regular submit (via the button or pressing enter) using "handleSubmit" function, and the alternative submit (via the other button) using "handleAlternate".

class Example extends React.Component {

  handleSubmit(event) {
    event.preventDefault();
    ....
  }

  handleAlternate(event) {
    event.preventDefault();
    ...
  }

  render() {
    <form onSubmit={this.handleSubmit.bind(this)}>
      ...
      <button type="submit">Submit</button>
      <button onClick={this.handleAlternate.bind(this)}>Alternate</button>
    </form>
  }

}

It seems to me that you shouldn't use onSubmit event. onSubmit is created to handle sending a form via POST request to the server, but your use case seems to be different.

I would use <button> element and onClick handler instead.

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