onKeyDown事件不适用于React中的div

reactjs React.js

小卤蛋村村

2020-03-13

我想在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);
  }

  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风格做更多。我试过了

        onKeyDown={this.onKeyPressed}

在组件上。但是它没有反应。我记得它可以处理输入元素。

码笔

我该怎么做?

第1458篇《onKeyDown事件不适用于React中的div》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
斯丁A 2020.03.13

您必须防止触发默认事件。

onKeyPressed(e) {
   e.preventDefault();
   console.log(e.key);
}
阿飞神乐 2020.03.13

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

神奇西里 2020.03.13

您在构造函数中缺少方法的绑定。这就是React建议您这样做的方式:

class Whatever {
  constructor() {
    super();
    this.onKeyPressed = this.onKeyPressed.bind(this);
  }

  onKeyPressed(e) {
    // your code ...
  }

  render() {
    return (<div onKeyDown={this.onKeyPressed} />);
  }
}

还有其他方法可以执行此操作,但这将是运行时最有效的方法。

理查德路易 2020.03.13

您在纯Javascript中考虑过多。摆脱那些React生命周期方法上的侦听器并使用event.key代替event.keyCode(因为这不是JS事件对象,所以它是React SyntheticEvent)。您的整个组件可能就这么简单(假设您尚未在构造函数中绑定方法)。

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

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

你需要这样写

<div 
    className="player"
    style={{ position: "absolute" }}
    onKeyDown={this.onKeyPressed}
    tabIndex="0"
  >

如果onKeyPressed未绑定this,则尝试使用箭头功能重写它或将其绑定到组件中constructor

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android