reactjs – onKeyDown事件不在React中的div上工作
发布时间:2020-12-15 20:54:42 所属栏目:百科 来源:网络整理
导读:我想在React中的div上使用keyDown事件.我做: componentWillMount() { document.addEventListener("keydown",this.onKeyPressed.bind(this)); } componentWillUnmount() { document.removeEventListener("keydown",this.onKeyPressed.bind(this)); } onKeyPr
我想在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”应该激活你的处理程序.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |