gpt4 book ai didi

javascript - 冲突事件 : onKeyPress & onClick

转载 作者:行者123 更新时间:2023-11-30 15:23:43 24 4
gpt4 key购买 nike

我有一个这样的:

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

在以下情况下,没有错误,我可以登录:

  1. 我用鼠标点击login按钮
  2. 我在登录按钮未获得焦点时按 Enter

但是下面的第三种情况,由于登录操作被调用两次而给我错误:

  1. 当我在登录按钮获得焦点时按 Enter(例如,登录按钮通过按 tab 键获得焦点)

我想知道可以避免第三种情况错误的最佳做法是什么。我查看了其他相关的 SO 问题,但我无法找出最佳做法。


我忘了说我正在使用 ReactJS 和 MobX。

最佳答案

通过移动 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>

关于javascript - 冲突事件 : onKeyPress & onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43303980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com