javascript - 冲突事件 : onKeyPress & onClick

标签 javascript html reactjs mobx mobx-react

我有一个这样的:

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. 我用鼠标单击登录按钮
  2. 我在登录按钮未聚焦时按 Enter

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

  • 当我在登录按钮处于焦点状态时按 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/

    相关文章:

    reactjs - React Native 纸张搜索栏在按键时关闭键盘

    alert - 更改 JavaScript Alert() 或 Prompt() 的外观

    javascript - Dojo Toolkit : dojox. charting.Data系列,如何连接到数据刷新事件?

    javascript - 插入到页外dom时保留脚本标签,然后使用jquery进行分页

    javascript - 将 SVG 复制到 Canvas 后出现神秘增长

    html - 即使行内容太大,如何限制 HTML 表格始终具有 100% 的高度

    javascript - react native : Import modules outside of project directory

    javascript - 在 React 中更新状态数组长度

    javascript - 如何获得选择框中所有值的列表?

    html - CSS:before 对某些元素不起作用,:after 可以正常工作