简体   繁体   中英

React form with multiple buttons - how to choose one to handle onSubmit event?

Let's say I have this HTML:

<div id="container"></div>

<p>Output: <span id="output"></span></p>

and this JS:

function otherAction(e) {
  document.getElementById('output').innerHTML = 'otherAction';
  e.preventDefault();
}

function submit(e) {
  document.getElementById('output').innerHTML = 'submit';
  e.preventDefault();
}

ReactDOM.render(
  <form onSubmit={submit}>
    <input type="text" defaultValue="foo" />
    <button onClick={otherAction}>Other Action</button>
    <button type="submit">Submit</button>
  </form>,
  document.getElementById('container')
);

Actually, let's not just say it, let's put it in a JSFiddle example . What I want to happen is that:

  1. Clicking the "Other Action" button triggers the otherAction function (it does!)

  2. Clicking the "Submit" button triggers the submit function (it does!)

  3. Putting your cursor in the text box and pressing enter triggers the submit function (this does not work currently!)

In #3, what happens instead is that otherAction gets triggered. How can I change that?

If you set the first button to type="button" it should work.

<button type="button" onClick={otherAction}>Other Action</button>

https://jsfiddle.net/L0urqamz/3/

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