与React一起使用时如何检测keyPress上的'Enter'键 [英] How to detect 'Enter' key on keyPress when used with React

查看:160
本文介绍了与React一起使用时如何检测keyPress上的'Enter'键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ReactJs开发我的应用程序.我试图通过处理onKeyPress事件按下Enter时提交输入文本.它检测其他输入,但不输入.我尝试了不同的方法-event.keyevent.charCodeevent.keyCodeevent.which ...似乎没有任何作用.

I am using ReactJs to develop my application. I am trying to submit an input text when Enter is pressed by handling the onKeyPress event. It detects other inputs, but not enter. I have tried different ways - event.key, event.charCode, event.keyCode, event.which... Nothing seems to work.

React.createElement("input", {tabIndex: "1", onKeyPress: this.handleKeyPress, onChange: this.handleChange, 
                           placeholder: "ex: 1,10,15"}), 

handleChange: function (event) {
        this.setState({userInputBuckets: event.target.value});
    },
handleKeyPress: function (event) {
        if (event.charCode == 13) {
            event.preventDefault();
            this.props.table.handleSubtotalBy(this.props.columnDef, this.state.userInputBuckets);
        }
    },

我也尝试使用onKewDown处理,它检测到正确的密钥,但是即使将event.keyCode == 13评估为true,它也不会执行if块.

I also tried with onKewDown handling, it detects the correct key, but it doesn't execute the if block even though it evaluates event.keyCode == 13 as true.

推荐答案

e.stopPropagataionhandleSubtotalBy移动到handleKeyPress:

handleKeyPress(event) {
  if (event.charCode == 13) {
    event.preventDefault();
    event.stopPropagation();
    this.props.table.handleSubtotalBy(this.props.columnDef, this.state.userInputBuckets);
  }
}


handleSubtotalBy(columnDef, partitions) { 
  const subtotalBy = this.state.subtotalBy || [];
  // ...
}

这篇关于与React一起使用时如何检测keyPress上的'Enter'键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆