React项目中button绑定onKeyPress键盘事件无法触发问题咨询
问题解答
关于onKeyPress的绑定限制说明
onKeyPress不是仅能和<div>配合使用,所有可聚焦元素(包括input、button、为div设置tabIndex属性后)都可以绑定键盘事件,你当前代码无法触发事件是存在多处编写错误。
具体错误点
- 构造函数中
handleKeyPress绑定逻辑错误:你编写的this.handleKeyPress=this.handleKeyPress(this)是直接调用了函数并把返回值(undefined)赋值给了实例方法,正确写法应该和handleClick一致,使用.bind(this)完成上下文绑定 - 键盘事件绑定对象不合理:你将
onKeyPress绑定在单个打击垫按钮上,只有该按钮处于聚焦状态时才会响应键盘事件,不符合鼓机全局响应键盘按键的需求 onKeyPress已被Web标准弃用,主流浏览器更推荐使用onKeyDown/onKeyUp替代,兼容性更稳定
修正代码示例
const keys={ "Q-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/SD0025.mp3", "W-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/SD0010.mp3", "E-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/SD0000.mp3", "A-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/RS.mp3", "S-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/OH25.mp3", "D-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/MA.mp3", "Z-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/CY0010.mp3", "X-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/CH.mp3", "C-pad":"https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/CB.mp3" } const keyboards=["Q","W","E","A","S","D","Z","X","C"] class App extends React.Component{ constructor(){ super() this.state={} this.handleClick = this.handleClick.bind(this) this.handleKeyDown = this.handleKeyDown.bind(this) } // 组件挂载后注册全局键盘监听 componentDidMount() { window.addEventListener('keydown', this.handleKeyDown) } // 组件卸载前移除监听,避免内存泄漏 componentWillUnmount() { window.removeEventListener('keydown', this.handleKeyDown) } handleKeyDown(event){ const pressKey = event.key.toUpperCase() if (keyboards.includes(pressKey)) { const playSound = new Audio(keys[`${pressKey}-pad`]) playSound.play() } } handleClick(event){ const {name} = event.target const playSound = new Audio(keys[name]) playSound.play() } render(){ const keyboardsComponent= keyboards.map((key,index)=>( <input type="button" className="drum-pad" id={key+'-pad'+index} value={key} name={key+'-pad'} onClick={this.handleClick} /> )) return( <div> <h1 className="title">Drum machine</h1> <div id="drum-machine" className="container"> {keyboardsComponent} </div> </div> ) } } ReactDOM.render(<App />, document.getElementById("app"));
内容的提问来源于stack exchange,提问作者John Huang
相关产品推荐
相关产品推荐

