onKeyDown 事件不适用于 React 中的 div [英] onKeyDown event not working on divs in React

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

问题描述

我想在 React 的 div 上使用 keyDown 事件.我愿意:

 componentWillMount() {document.addEventListener(keydown", this.onKeyPressed.bind(this));}componentWillUnmount() {document.removeEventListener(keydown", this.onKeyPressed.bind(this));}onKeyPressed(e) {console.log(e.keyCode);}使成为() {让玩家 = this.props.boards.dungeons[this.props.boards.currentBoard].player;返回 (

)}

它工作得很好,但我想以 React 风格做更多.我试过了

onKeyDown={this.onKeyPressed}

在组件上.但它没有反应.我记得它适用于输入元素.

代码笔

我该怎么做?

解决方案

你应该使用 tabIndex 属性来监听 React 中 div 上的 onKeyDown 事件.设置 tabIndex=0" 应该会触发您的处理程序.

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>
    )
  }

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

How can I do it?

解决方案

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天全站免登陆