问题描述
我想在单击链接后提交一个React表单.
I want to submit a React form after a click on a link.
为此,如果单击链接,我需要以编程方式提交表单.
To do so I need to submit the form programmatically if the link is clicked.
我的问题是:提交表单后未触发onSubmit
处理程序.
my problem is : onSubmit
handler is not being fired after the form submit .
这是我为此目的而编写的代码:
Here is a code snipped that I made for this purpose:
var MyForm = React.createClass({
handleSubmit: function(e){
console.log('Form submited');
e.preventDefault();
},
submitForm : function(e){
this.refs.formToSubmit.submit();
},
render: function() {
return (
<form ref="formToSubmit" onSubmit={this.handleSubmit}>
<input name='myInput'/>
<a onClick={this.submitForm}>Validate</a>
</form>);
}
});
ReactDOM.render(
<MyForm name="World" />,
document.getElementById('container')
);
handleSubmit
不会被调用,并且将执行默认行为(正在提交表单).这是ReactJs错误还是正常行为?有没有一种方法可以调用onSubmit处理程序?
The handleSubmit
is not invoked and the default behavior is executed (the form being submitted).Is this a ReactJs bug or a normal behavior?Is there a way to get the onSubmit handler invoked ?
推荐答案
我在此方面取得了成功.单击后触发handleSubmit.希望这会有所帮助.
I have success with this. This triggers the handleSubmit upon clicking. Hope this helps.
<form
onSubmit={this.handleSubmit}
ref={ (ref) => { this.form = ref; } }
>
<a onClick={ () => { this.form.dispatchEvent(new Event('submit')) } }>
Validate
</a>
</form>
从这里找到: https://github.com/facebook/react/issues/6796
这篇关于React.js:以编程方式提交表单不会触发onSubmit事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!