我正在使用 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);
}
},
我还尝试使用 onKewDown
处理,它检测到正确的键,但它不执行 if block ,即使它评估 event.keyCode == 13
为是的。
最佳答案
将 e.stopPropagataion
从 handleSubtotalBy
移动到 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 || [];
// ...
}
关于javascript - 与 React 一起使用时如何检测 keyPress 上的 'Enter' 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44958938/