我想在React中的div上使用keyDown事件。我這樣做:onKeyDown事件不適用於React中的div
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}
上的組件。但它沒有反應。我記得它適用於輸入元素。
Codepen:http://codepen.io/lafisrap/pen/OmyBYG
我該怎麼辦呢?
對不起。我確信,我只是忽略了這一點。但這不是問題。它仍然不起作用。 – Michael
已更新的答案。您應該在按任意鍵之前點擊div或將其聚焦。 – Panther
我做到了。它不工作。我更新了上面的代碼。它適用於DOM命令,但不適用於React樣式。 – Michael