2017-04-09 98 views
1

我有一個從這樣的:衝突事件:onkeypress事件&的onClick

enter image description here

用下面的代碼:

<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 
    } 
} 

在以下情況下,沒有錯誤,我可以l ogin:

  1. 我點擊login按鈕,鼠標
  2. 我按輸入而登錄按鈕不集中

但接下來的第三方案,使我的錯誤是由於登錄操作被調用兩次:

  1. 當我按輸入登錄按鈕IS focu

SED(例如登錄按鈕被按下標籤重點關注)我不知道什麼是我能避免第三方案的錯誤的最佳實踐。我查看了其他相關的SO問題,但我無法弄清楚最佳做法。


我忘了提及我在使用ReactJS和MobX。

+0

請t用你使用的框架來解決問題。處理點擊和輸入提交的方式是隻綁定提交併提交按鈕 – mplungjan

+0

@mplungjan謝謝,我添加了ReactJS和MobX標籤 – user3405291

+0

http://stackoverflow.com/questions/38262148/react-handle-form - 提交 – mplungjan

回答

1

通過移動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> 
1

它是否適合你的使用情況,您也可以使用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> 
    ); 
    } 
}