简体   繁体   English

如何防止表单过帐 <input type=submit> 点击使用React

[英]How to prevent form posting in <input type=submit> on click using React

I have this in my jsx file: 我的jsx文件中有这个:

<input type="submit" onClick={() => this.validateForm()} id="account-submit" value="Sign Up" />

The function validateForm gets called but after that, the default behavior of submit button posting the form is done so a reload of the page is done. 函数validateForm被调用,但是此后,完成了提交表单后的提交按钮的默认行为,从而完成了页面的重新加载。 How can I trigger only the onClick function and prevent the submit from happening to prevent reload? 如何仅触发onClick函数并阻止提交以防止重新加载?

EDIT - Added this based on answer 编辑-根据答案添加了此内容

validateForm: function (e) {
    e.preventDefault();
}

e is undefined e未定义

You can use e.preventDefault() . 您可以使用e.preventDefault() You can change your input element as: 您可以将input元素更改为:

<input type="submit" onClick={this.validateForm} id="account-submit" value="Sign Up" />

And in the validateForm function: 并在validateForm函数中:

validateForm = e => {
    e.preventDefault(); 
    // your code here
}

Update: 更新:

If you use the arrow function in the validateForm like my example, I believe it will work fine. 如果像我的示例一样在validateForm使用箭头功能,我相信它会正常工作。

If you want to use the function(e) like your added code, you should change a few things. 如果您想像添加的代码一样使用function(e) ,则应进行一些更改。 In your input tag: 在您的input标签中:

<input type="submit" onClick={e => this.validateForm(e)} id="account-submit" value="Sign Up" />

In your validateForm function: 在您的validateForm函数中:

validateForm = function(e) {
    console.log('Hello world');
    console.log(e);
}

The code above works fine for me. 上面的代码对我来说很好用。 You should really understand the different when you use arrow function (provide in ES6) and normal function (provide in older ES). 使用箭头功能(在ES6中提供)和普通功能(在较旧的ES中提供)时,您应该真正理解它们的区别。 If you don't know what the arrow function is, it's time to extend your knowledge. 如果您不知道箭头功能是什么,那么该扩展您的知识了。

Good luck and code fun! 祝您好运,并享受代码乐趣!

I am just explaining what @delig29 just said. 我只是在解释@ delig29刚才说的内容。

When you make an <input type="submit" onClick={this.onSubmitForm} /> The onClick function for the submit type button fires an event and passes it to the onClick method which is this.onSubmitForm . 当您创建<input type="submit" onClick={this.onSubmitForm} /> ,提交类型按钮的onClick函数会触发一个事件并将其传递给this.onSubmitForm的onClick方法。

When you define this function which is going to be something like this 当您定义此功能时,将是这样的

onSubmitForm = (e) => { // Here I am passing e(event) as a @param
  // This method call of the event **preventDefault** will
  // trigger an event which will disable the browsers default behavior 
  // to reload the page on hitting form submit 
  e.preventDefault(); 
  /**
  ** Do Whatever You Want Here With Your Code
  **/
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM