[英]Conflicting events: onKeyPress & onClick
我有一個像這樣的:
使用以下代碼:
<form onKeyPress={this.login.bind(this)}>
<input type="text" placeholder="username"/>
<input type="password" placeholder="password"/>
<button type="button" onClick={this.login.bind(this)}>Log In</button>
</form>
雖然我有如下的login()
方法:
login(e){
if((e.type==='keypress' && e.which===13) || e.type==='click'){
//Do login operations:
this.props.store.login()//the method inside MobX store
}
}
在以下情況下,沒有錯誤,我可以登錄:
login
按鈕 但是以下第三種情況由於兩次登錄操作而給我錯誤:
我想知道如何避免第三種情況的錯誤的最佳實踐是什么。 我瀏覽了其他相關的SO問題,但是我找不到最佳實踐。
我忘了提到我在MobX中使用ReactJS。
通過將onKeyPress
屬性從<form>
標記移動到文本類型<input>
標記來解決此問題:
<form>
<input type="text" placeholder="username" onKeyPress={this.login.bind(this)}/>
<input type="password" placeholder="password" onKeyPress={this.login.bind(this)}/>
<button type="button" onClick={this.login.bind(this)}>Log In</button>
</form>
如果更適合您的用例,也可以使用onSubmit
事件:
例子( JS Bin )
class App extends Component {
login = (e) => {
e.preventDefault();
console.log('login');
}
render() {
return (
<form onSubmit={this.login}>
<input type="text" placeholder="username" />
<input type="password" placeholder="password" />
<button type="submit">Log In</button>
</form>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.