我想在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”应该激活你的处理程序.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。