React - 防止表单提交 [英] React - Preventing Form Submission
问题描述
我一直在试验 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>
</p>
</Form>
我错过了什么?
推荐答案
我认为首先值得注意的是,如果没有 javascript(纯 html),form
元素在单击 <input type="submit" value="submit form">
或 .在 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,控制台,输出
这篇关于React - 防止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!