简体   繁体   中英

Windows Event KeyPress

I would like to know if it is possible to activate an event with keyboard arrows, directly on the page, without having to have the mouse in an input or something like this, I tried this and it did not work.

keyPress (e){
 if(e.key == "ArrowLeft"){
   console.log(e.key)
 }
}

Yes you can do it. But when you call it, it is not on keyPress instead on keyDown .

You can add an eventListener to listen to keypress in componentDidMount .

  componentDidMount(){ window.addEventListener('keydown', this.keyPress); } componentWillUnmount(){ window.removeEventListener('keydown', this.keyPress); } keyPress (e){ if(e.key == "ArrowLeft"){ console.log(e.key) } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM