我想在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}
在组件上.但它没有反应.我记得它适用于输入元素.
Codepen:http://codepen.io/lafisrap/pen/OmyBYG
我该怎么做?
您应该使用tabIndex属性来侦听React中div上的onKeyDown事件.设置tabIndex =“0”应该激活你的处理程序.