在 React.js 中设置 onSubmit

在提交表单时,我尝试使用 doSomething()代替默认的发帖行为。

显然,在反应,OnSubmit 是表单支持的事件。然而,当我尝试以下代码:

var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(){
alert('it works!');
}


return <form onSubmit={doSomething}>
<button>Click me</button>
</form>;
}
});

方法 doSomething()运行,但此后,默认的 post 行为仍然执行。

你可以用我的 Jsfiddle测试一下。

我的问题是: 如何防止默认的发帖行为?

203284 次浏览

In your doSomething() function, pass in the event e and use e.preventDefault().

doSomething = function (e) {
alert('it works!');
e.preventDefault();
}

You can pass the event as argument to the function and then prevent the default behaviour.

var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(event){
event.preventDefault();
alert('it works!');
}


return <form onSubmit={this.doSomething}>
<button>Click me</button>
</form>;
}
});

I'd also suggest moving the event handler outside render.

var OnSubmitTest = React.createClass({


submit: function(e){
e.preventDefault();
alert('it works!');
}


render: function() {
return (
<form onSubmit={this.submit}>
<button>Click me</button>
</form>
);
}
});
<form onSubmit={(e) => {this.doSomething(); e.preventDefault();}}></form>

it work fine for me