簡體   English   中英

沖突事件:onKeyPress和onClick

[英]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
    }
}

在以下情況下,沒有錯誤,我可以登錄:

  1. 我用鼠標點擊login按鈕
  2. 當登錄按鈕未聚焦時,我按Enter

但是以下第三種情況由於兩次登錄操作而給我錯誤:

  1. 當登錄按鈕處於焦點狀態時按Enter鍵(例如,按Tab鍵使登錄按鈕處於焦點狀態)

我想知道如何避免第三種情況的錯誤的最佳實踐是什么。 我瀏覽了其他相關的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM