react自动触发表单提交_javascript-React-防止表单提交

这篇博客探讨了在React应用中如何防止HTML表单在点击按钮时自动提交。作者分享了使用React事件处理程序如`e.preventDefault()`以及设置按钮`type="button"`属性来避免表单提交的方法。此外,还提供了多个示例代码供参考。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值