Javascript 在 React.js 中设置 onSubmit
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28479239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting onSubmit in React.js
提问by Lucas du Toit
On submission of a form, I'm trying to doSomething()instead of the default post behaviour.
在提交表单时,我试图doSomething()代替默认的发布行为。
Apparently in React, onSubmit is a supported event for forms.However, when I try the following code:
显然在 React 中,onSubmit 是表单支持的事件。但是,当我尝试以下代码时:
var OnSubmitTest = React.createClass({
render: function() {
doSomething = function(){
alert('it works!');
}
return <form onSubmit={doSomething}>
<button>Click me</button>
</form>;
}
});
The method doSomething()is run, but thereafter, the default post behaviour is still carried out.
该方法doSomething()已运行,但此后仍会执行默认的发布行为。
You can test this in my jsfiddle.
您可以在我的jsfiddle 中对此进行测试。
My question: How do I prevent the default post behaviour?
我的问题:如何防止默认发布行为?
回答by Henrik Andersson
In your doSomething()function, pass in the event eand use e.preventDefault().
在您的doSomething()函数中,传入事件e并使用e.preventDefault().
doSomething = function (e) {
alert('it works!');
e.preventDefault();
}
回答by Adam Stone
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>
);
}
});
回答by Truong
<form onSubmit={(e) => {this.doSomething(); e.preventDefault();}}></form>
it work fine for me
它对我来说很好用
回答by Bolza
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>;
}
});

