1

我有一个这样的:

在此处输入图像描述

使用以下代码:

<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 问题,但我无法找出最佳实践。


我忘了提到我正在将 ReactJS 与 MobX 一起使用。

4

2 回答 2

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>
    );
  }
}
于 2017-04-10T08:51:21.740 回答
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>
于 2017-04-09T10:16:05.090 回答