在 reactjs 中收听文档的按键 [英] Listen to keypress for document in reactjs
问题描述
我想绑定以关闭 escape
上的 active react bootstrap popover.这是代码
_handleEscKey:function(event){控制台日志(事件);如果(事件.keyCode == 27){this.state.activePopover.hide();}},componentWillMount:function(){BannerDataStore.addChangeListener(this._onchange);document.addEventListener("click", this._handleDocumentClick, false);document.addEventListener("keyPress", this._handleEscKey, false);},componentWillUnmount:函数(){BannerDataStore.removeChangeListener(this._onchange);document.removeEventListener("click", this._handleDocumentClick, false);document.removeEventListener("keyPress", this._handleEscKey, false);},
但是当我按任意键时,控制台中没有任何记录.我也试过在窗口上和不同的情况下听.'keypress'、'keyup' 等,但似乎我做错了什么.
你应该使用 keydown
而不是 keypress
.
Keypress(已弃用)通常仅用于根据文档产生字符输出的键
<块引用>当一个键被按下并且该键通常会产生一个字符值时会触发 keypress 事件
按键><块引用>
当按下某个键时会触发 keydown 事件.
I want to bind to close the active react bootstrap popover on escape
press .Here is the code
_handleEscKey:function(event){
console.log(event);
if(event.keyCode == 27){
this.state.activePopover.hide();
}
},
componentWillMount:function(){
BannerDataStore.addChangeListener(this._onchange);
document.addEventListener("click", this._handleDocumentClick, false);
document.addEventListener("keyPress", this._handleEscKey, false);
},
componentWillUnmount: function() {
BannerDataStore.removeChangeListener(this._onchange);
document.removeEventListener("click", this._handleDocumentClick, false);
document.removeEventListener("keyPress", this._handleEscKey, false);
},
But nothing is getting logged in the console when I press any key. I have tried to listen that on window also and with different cases .'keypress','keyup' etc but it seem I am doing something wrong .
You should use keydown
and not keypress
.
Keypress (deprecated) is usually used only for keys that produce a character output as per the docs
The keypress event is fired when a key is pressed down and that key normally produces a character value
The keydown event is fired when a key is pressed down.
这篇关于在 reactjs 中收听文档的按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!