Som*_*ser 55 javascript reactjs
我一直在试验React.在我的实验性功能,我使用的是Reactstrap框架.当我点击一个按钮,我已经注意到,HTML表单提交.有没有办法在单击按钮时阻止表单提交?
我在这里重新创建了我的问题.我的表单很基本,看起来像这样:
<Form>
<h3>Buttons</h3>
<p>
<Button color="primary" onClick={this.onTestClick}>primary</Button>
</p>
</Form>
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
edd*_*ere 65
我认为首先值得注意的是,如果没有javascript(普通的html),form
当点击<input type="submit" value="submit form">
或时,元素会提交<button>submits form too</button>
.在javascript中,您可以通过使用事件处理程序并调用e.preventDefault()
按钮单击或表单提交来防止这种情况.e
是传递给事件处理程序的事件对象.通过反应,两个相关的事件处理程序可以通过表单作为onSubmit
,另一个通过按钮通过onClick
.
示例:http://jsbin.com/vowuley/edit?html,js,console,output
Hau*_*Haf 48
没有JS真正需要......只需type
向按钮添加属性值为的属性button
<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>
Run Code Online (Sandbox Code Playgroud)
默认情况下,按钮元素的类型为"submit",这使得它们提交其封闭的表单元素(如果有).更改type
为"按钮"可以防止这种情况发生.
Paw*_*wel 18
preventDefault是你正在寻找的.只是阻止按钮提交
<Button onClick={this.onClickButton} ...
Run Code Online (Sandbox Code Playgroud)
码
onClickButton (event) {
event.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)
如果您有一个要以自定义方式处理的表单,则可以捕获更高级别的事件onSubmit,这也将阻止该按钮提交.
<form onSubmit={this.onSubmit}>
Run Code Online (Sandbox Code Playgroud)
在代码中
onSubmit (event) {
event.preventDefault();
// custom form handling here
}
Run Code Online (Sandbox Code Playgroud)
Yon*_*wit 13
确保将 onSubmit 属性放在表单上而不是按钮上,以防万一您有 from。
<form onSubmit={e => e.preventDefault()}>
<button onClick={this.handleClick}>Click Me</button>
</form>
Run Code Online (Sandbox Code Playgroud)
确保将按钮 onClick 属性更改为您的自定义函数。
2种方式
首先,我们将参数中的事件传递给onClick.
onTestClick(e) {
e.preventDefault();
alert('here');
}
Run Code Online (Sandbox Code Playgroud)
// Look here we pass the args in the onClick
<Button color="primary" onClick={e => this.onTestClick(e)}>primary</Button>
Run Code Online (Sandbox Code Playgroud)
第二个我们将它传递给参数,我们在onClick中做得很好
onTestClick() {
alert('here');
}
Run Code Online (Sandbox Code Playgroud)
// Here we did right inside the onClick, but this is the best way
<Button color="primary" onClick={e => (e.preventDefault(), this.onTestClick())}>primary</Button>
Run Code Online (Sandbox Code Playgroud)
希望能有所帮助
归档时间: |
|
查看次数: |
57811 次 |
最近记录: |