【发布时间】:2017-09-16 04:03:44
【问题描述】:
我想在 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}
在组件上。但它没有反应。我记得它适用于输入元素。
我该怎么做?
【问题讨论】:
-
我个人喜欢你的方法。这看起来像是将击键绑定到文档的好方法,这超出了组件的范围。并且不需要专注于特定元素。
标签: reactjs events keypress keydown