onKeyDown事件不在React中的div上 [英] onKeyDown event not working on divs in React

查看:264
本文介绍了onKeyDown事件不在React中的div上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在React的div上使用keyDown事件。我做:

I want to use a keyDown event on a div in React. I do:

  componentWillMount() {
      document.addEventListener("keydown", this.onKeyPressed.bind(this));
  }

  componentWillUnmount() {
      document.removeEventListener("keydown", this.onKeyPressed.bind(this));
  }      

  onKeyPressed(e) {
    console.log(e.keyCode);
  }

  render() {
    let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
    return (
      <div 
        className="player"
        style={{ position: "absolute" }}
        onKeyDown={this.onKeyPressed} // not working
      >
        <div className="light-circle">
          <div className="image-wrapper">
            <img src={IMG_URL+player.img} />
          </div>
        </div>
      </div>
    )
  }

它工作正常,但我想在React样式中做更多。我试过

It works fine, but I would like to do it more in React style. I tried

        onKeyDown={this.onKeyPressed}

上的组件。但它没有反应。我记得,它适用于输入元素。

on the component. But it doesn't react. It works on input elements as I recall.

Codepen: http://codepen.io/lafisrap/pen/OmyBYG

我该怎么做?

推荐答案

您应该使用 tabIndex 属性来侦听React中的div上的KeyDown事件。设置tabIndex =0应该触发你的处理程序。

You should use tabIndex attribute to be able to listen onKeyDown event on a div in React. Setting tabIndex="0" should fire your handler.

这篇关于onKeyDown事件不在React中的div上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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