React - 阻止表单提交

2022-01-31 00:00:00 reactjs javascript

我一直在尝试使用 React.在我的实验中,我使用的是 Reactstrap 框架.当我点击一个按钮时,我注意到 HTML 表单提交了.有没有办法在单击按钮时阻止表单提交?

I've been experimenting with React. In my experiement, I'm using the Reactstrap framework.When I click a button, I've noticed that the HTML form submits. Is there a way to prevent form submission when a button is clicked?

我在这里重新创建了我的问题.我的表单非常基本,如下所示:

I've recreated my issue here. My form is pretty basic and looks like this:

<Form>
  <h3>Buttons</h3> 
  <p>
    <Button color="primary" onClick={this.onTestClick}>primary</Button>&nbsp;
  </p>
</Form>

我错过了什么?

推荐答案

我认为首先值得注意的是,如果没有 javascript(纯 html),则在单击 < 时会提交 form 元素;input type="submit" value="submit form"><button>也提交表单</button>.在 javascript 中,您可以通过使用事件处理程序并在按钮单击或表单提交时调用 e.preventDefault() 来防止这种情况.e 是传递给事件处理程序的事件对象.使用 react,两个相关的事件处理程序可以通过表单作为 onSubmit 使用,另一个在按钮上通过 onClick 使用.

I think it's first worth noting that without javascript (plain html), the form element submits when clicking either the <input type="submit" value="submit form"> or <button>submits form too</button>. In javascript you can prevent that by using an event handler and calling e.preventDefault() on button click, or form submit. e is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit, and the other on the button via onClick.

示例:http://jsbin.com/vowuley/edit?html,js,控制台,输出

相关文章