React 实现键盘监听事件
1、在需要进行监听的Dom上添加 onKeyDown 方法:
<Button className='btn-add' type="primary" icon="search" onKeyDown={(e)=>this.handleKeyDown(e)} onClick={()=>this.handleSearch()}> {LangMapping.Search} </Button>
2、定义 handleKeyDown 方法及事件处理:
//keyCode 38=up arrow 40=down arrow 13=Enter handleKeyDown = (e) => { if (e.keyCode === 13) { console.log("按下了Enter键") this.handleSearch(); } }
3、在 componentDidMount 钩子中定义键盘监听事件:
componentDidMount() { document.addEventListener('keydown',this.handleKeyDown); }
4、在 componentWillUnmount 钩子中移除键盘监听事件:
componentWillUnmount() { document.removeEventListener('keydown',this.handleKeyDown); }
5、参考:
https://www.cnblogs.com/iverson-tian/p/13640450.html