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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM