javascript-React-防止表单提交
我一直在试验React。 在我的实验中,我使用的是Reactstrap框架。单击按钮时,我注意到HTML表单已提交。 有没有一种方法可以防止单击按钮时提交表单?
我在这里重新创建了我的问题。 我的表单非常基本,看起来像这样:
Buttons
primary
我想念什么?
9个解决方案
62 votes
我认为首先要注意的是,如果没有JavaScript(纯HTML),则单击或submits form too时会提交form元素。在javascript中,您可以通过使用事件处理程序并在按钮单击或表单提交上调用e.preventDefault()来防止这种情况。 e是传递到事件处理程序中的事件对象。 通过react,两个相关的事件处理程序可以通过onSubmit的形式使用,另一个通过onClick在按钮上使用。
示例:[http://jsbin.com/vowuley/edit?html,js,console,output]
eddywashere answered 2020-01-04T02:03:46Z
46 votes
真的不需要JS ...只需向按钮添加type属性即可,其属性值为button
primary
默认情况下,按钮元素的类型为“提交”,这会使它们提交其封闭的表单元素(如果有)。 将type更改为“按钮”可以防止这种情况。
HaukurHaf answered 2020-01-04T02:04:10Z
18 votes
preventDefault是您要寻找的。 只是阻止按钮提交
码
onClickButton (event) {
event.preventDefault();
}
如果您具有要以自定义方式处理的表单,则可以捕获onSubmit上的更高级别的事件,这也将阻止该按钮的提交。
及以上代码
onSubmit (event) {
event.preventDefault();
// custom form handling here
}
Pawel answered 2020-01-04T02:04:43Z
6 votes
2种方式
首先,我们将参数中的事件直接传递给onClick。
onTestClick(e) {
e.preventDefault();
alert('here');
}
// Look here we pass the args in the onClick
this.onTestClick(e)}>primary
第二个,我们将其传递给参数,然后在onClick中做对了
onTestClick() {
alert('here');
}
// Here we did right inside the onClick, but this is the best way
(e.preventDefault(), this.onTestClick())}>primary
希望能有所帮助
EQuimper answered 2020-01-04T02:05:16Z
1 votes
在您的onTestClick函数中,传递事件参数并对其调用preventDefault()。
function onTestClick(e) {
e.preventDefault();
}
Soviut answered 2020-01-04T02:05:36Z
1 votes
function onTestClick(evt) {
evt.stopPropagation();
}
fvgs answered 2020-01-04T02:05:52Z
1 votes
您已阻止事件的默认操作,并从该函数返回false。
function onTestClick(e) {
e.preventDefault();
return false;
}
Gökhan Kurt answered 2020-01-04T02:06:12Z
1 votes
确保您将onSubmit属性(而不是按钮)放在表单上,以防万一。
{e.preventDefault();}}>Click Me
确保将按钮onClick功能更改为自定义功能。
Yonatan Dawit answered 2020-01-04T02:06:36Z
-3 votes
componentDidUpdate(){
$(".wpcf7-submit").click( function(event) {
event.preventDefault();
})
}
您可以使用componentDidUpdate和event.preventDefault()禁用表单提交。因为react不支持返回false。
prajakta gadhave answered 2020-01-04T02:06:56Z