简体   繁体   English

React - 防止表单提交

[英]React - Preventing Form Submission

I've been experimenting with React.我一直在试验 React。 In my experiement, I'm using the Reactstrap framework .When I click a button, I've noticed that the HTML form submits.在我的实验中,我使用的是Reactstrap 框架。当我单击一个按钮时,我注意到提交了 HTML 表单。 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>&nbsp;
  </p>
</Form>

What am I missing?我错过了什么?

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> .我认为首先值得注意的是,如果没有 javascript(纯 html), form元素会在单击<input type="submit" value="submit form"><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.在 javascript 中,您可以通过使用事件处理程序并在按钮单击或表单提交时调用e.preventDefault()来防止这种情况发生。 e is the event object passed into the event handler. e是传递给事件处理程序的事件对象。 With react, the two relevant event handlers are available via the form as onSubmit , and the other on the button via onClick .使用 react,两个相关的事件处理程序可以通过表单onSubmit ,另一个通过onClick在按钮上。

Example: http://jsbin.com/vowuley/edit?html,js,console,output示例: http : //jsbin.com/vowuley/edit?html,js,console,output

No JS needed really ... Just add a type attribute to the button with a value of button真的不需要 JS ... 只需为按钮添加一个type属性,其值为button

<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>&nbsp;

By default, button elements are of the type "submit" which causes them to submit their enclosing form element (if any).默认情况下,按钮元素属于“提交”类型,这会导致它们提交其封闭的表单元素(如果有)。 Changing the type to "button" prevents that.type更改为“按钮”可以防止这种情况。

preventDefault is what you're looking for. preventDefault是您要查找的内容。 To just block the button from submitting只是阻止按钮提交

<Button onClick={this.onClickButton} ...

code代码

onClickButton (event) {
  event.preventDefault();
}

If you have a form which you want to handle in a custom way you can capture a higher level event onSubmit which will also stop that button from submitting.如果您有一个想要以自定义方式处理的表单,您可以捕获更高级别的 onSubmit 事件,这也将阻止该按钮提交。

<form onSubmit={this.onSubmit}>

and above in code及以上代码

onSubmit (event) {
  event.preventDefault();

  // custom form handling here
}

Make sure you put the onSubmit attribute on the form not the button in case you have a from.确保将 onSubmit 属性放在表单上而不是按钮上,以防您有 from。

<form onSubmit={e => e.preventDefault()}>
    <button onClick={this.handleClick}>Click Me</button>
</form>

Make sure to change the button onClick attribute to your custom function.确保将按钮 onClick 属性更改为您的自定义函数。

2 ways 2种方式

First one we pass the event in the argument right into the onClick.第一个我们将参数中的事件直接传递到 onClick 中。

  onTestClick(e) {
    e.preventDefault();
    alert('here');
  }

  // Look here we pass the args in the onClick
  <Button color="primary" onClick={e => this.onTestClick(e)}>primary</Button>&nbsp;

Second one we pass it into argument and we did right in the onClick第二个我们将它传递给参数,我们在 onClick 中做到了

  onTestClick() {
    alert('here');
  }

  // Here we did right inside the onClick, but this is the best way
  <Button color="primary" onClick={e => (e.preventDefault(), this.onTestClick())}>primary</Button>&nbsp;

Hope that can help希望能帮上忙

import React, { Component } from 'react';

export class Form extends Component {
  constructor(props) {
    super();
    this.state = {
      username: '',
    };
  }
  handleUsername = (event) => {
    this.setState({
      username: event.target.value,
    });
  };

  submited = (event) => {
    alert(`Username: ${this.state.username},`);
    event.preventDefault();
  };
  render() {
    return (
      <div>
        <form onSubmit={this.submited}>
          <label>Username:</label>
          <input
            type="text"
            value={this.state.username}
            onChange={this.handleUsername}
          />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

export default Form;

You have prevent the default action of the event and return false from the function.您已阻止事件的默认操作并从函数返回false

function onTestClick(e) {
    e.preventDefault();
    return false;
}

There's another, more accessible solution: Don't put the action on your buttons.还有另一个更易于使用的解决方案:不要将操作放在按钮上。 There's a lot of functionality built into forms already.表单中已经内置了很多功能。 Instead of handling button presses, handle form submissions and resets.处理表单提交和重置,而不是处理按钮按下。 Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.只需将onSubmit={handleSubmit}onReset={handleReset}到您的form元素中。

To stop the actual submission just include event in your function and an event.preventDefault();要停止实际提交,只需在您的函数中包含eventevent.preventDefault(); to stop the default submission behavior.停止默认提交行为。 Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.现在,从可访问性的角度来看,您的表单行为正确,并且您正在处理用户可能采取的任何形式的提交。

In your onTestClick function, pass in the event argument and call preventDefault() on it.在您的onTestClick函数中,传入事件参数并对其调用preventDefault()

function onTestClick(e) {
    e.preventDefault();
}
function onTestClick(evt) {
  evt.stopPropagation();
}
componentDidUpdate(){               
    $(".wpcf7-submit").click( function(event) {
        event.preventDefault();
    })
}

You can use componentDidUpdate and event.preventDefault() to disable form submission.As react does not support return false.您可以使用componentDidUpdateevent.preventDefault()来禁用表单提交。因为 react 不支持 return false。

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

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