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