React - Preventing Form Submission

前端 未结 11 817
一个人的身影
一个人的身影 2020-11-27 06:35

I\'ve been experimenting with React. In my experiement, I\'m using the Reactstrap framework.When I click a button, I\'ve noticed that the HTML form submits. Is there a way t

相关标签:
11条回答
  • 2020-11-27 07:10

    In your onTestClick function, pass in the event argument and call preventDefault() on it.

    function onTestClick(e) {
        e.preventDefault();
    }
    
    0 讨论(0)
  • 2020-11-27 07:12

    You have prevent the default action of the event and return false from the function.

    function onTestClick(e) {
        e.preventDefault();
        return false;
    }
    
    0 讨论(0)
  • 2020-11-27 07:14

    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>. In javascript you can prevent that by using an event handler and calling e.preventDefault() on button click, or form submit. e is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit, and the other on the button via onClick.

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

    0 讨论(0)
  • 2020-11-27 07:18

    Make sure you put the onSubmit attribute on the form not the button in case you have a 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.

    0 讨论(0)
  • 2020-11-27 07:28

    No JS needed really ... Just add a type attribute to the button with a value of 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.

    0 讨论(0)
  • 2020-11-27 07:28
    function onTestClick(evt) {
      evt.stopPropagation();
    }
    
    0 讨论(0)
提交回复
热议问题