在 reactjs 中收听文档的按键 [英] Listen to keypress for document in reactjs

查看:29
本文介绍了在 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

Keypress (deprecated)

The keypress event is fired when a key is pressed down and that key normally produces a character value

Keydown

The keydown event is fired when a key is pressed down.

这篇关于在 reactjs 中收听文档的按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆