防止 React 捕获制表符 [英] Prevent React from capturing tab character
问题描述
我有一个输入字段.我想让 React 检查是否在此字段中按下了选项卡.如果是,则处理该字段的内容(例如 ajax 调用).
I have an input field. I want React to check if a tab has been pressed in this field. If so, then process the contents of that field (e.g. ajax call).
getInitialState: function() {
return { name: "" };
},
handleChangeName: function(e) {
this.setState({name: e.target.value});
},
handleKeyUp: function(e) {
if (e.keyCode == 9) {
e.preventDefault();
alert("Execute ajax call after tab pressed");
}
},
<input type="text" value={this.state.name} onChange={this.handleChangeName}
onKeyDown={this.handleKeyUp} />
问题:
Tab 按键被拦截并执行后续代码,但将制表符插入到输入文本字段中.我如何防止这种情况发生?
Tab keypress is intercepted and subsequent code executed but the tab character is inserted into the input text field. How do I prevent this from happening?
我尝试了 preventDefault
、stopPropagation
、stopImmediatePropagation
的各种组合.我可以得到没有在输入文本字段中插入更多字符的结果,但随后没有执行任何代码.
I have tried various combinations of preventDefault
, stopPropagation
, stopImmediatePropagation
. I can get a result of no further chars being inserted into the input text field, but then no subsequent code is executed.
我错过了什么?
推荐答案
onKeyUp 或 onKeyPress 事件在 'Tab 时不会被调用>' 被按下是因为它之前触发了 onBlur,你需要用 onKeyDown 来捕捉它.您可以尝试使用事件 key 而不是 keyCode,如上例所示.
The events onKeyUp or onKeyPress won't be called when 'Tab' is pressed because it triggers a onBlur before, you need to catch it with onKeyDown. You can try to use the event key instead of keyCode, as the example above.
功能:
handleKeyDown: function(e) {
if (e.key === "Tab") {
e.preventDefault();
alert("Execute ajax call after tab pressed");
}
}
输入:
<input type="text" onKeyDown={this.handleKeyDown} />
希望对您有所帮助;)
这篇关于防止 React 捕获制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!