与 React 一起使用时如何检测 keyPress 上的“Enter”键

sau*_*umj 3 javascript keypress onkeypress reactjs

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

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);
        }
    },
Run Code Online (Sandbox Code Playgroud)

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

joe*_*ews 5

移动e.stopPropagataion距离handleSubtotalByhandleKeyPress

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 || [];
  // ...
}
Run Code Online (Sandbox Code Playgroud)