How to detect 'Enter' key on keyPress when used with React

拈花ヽ惹草 提交于 2020-12-10 18:33:35

问题


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);
        }
    },

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.


回答1:


Move e.stopPropagataion from handleSubtotalBy into 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 || [];
  // ...
}



回答2:


Given answer is not complete,

use

var code = event.keyCode || event.charCode

to support all browser:

Other than this, given answer is correct. Copy that.



来源:https://stackoverflow.com/questions/44958938/how-to-detect-enter-key-on-keypress-when-used-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!