问题描述
我正在使用ReactJs开发我的应用程序.我试图通过处理onKeyPress事件按下Enter时提交输入文本.它检测其他输入,但不输入.我尝试了不同的方法-event.key
,event.charCode
,event.keyCode
,event.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.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 || [];
// ...
}
这篇关于与React一起使用时如何检测keyPress上的'Enter'键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!