How to detect Esc Key Press in React and how to handle it

前端 未结 5 926
梦如初夏
梦如初夏 2021-01-30 00:02

How do I detect Esc keypress on reactjs? The similar thing to jquery

$(document).keyup(function(e) {
     if (e.keyCode == 27) { // escape key maps to keycode `         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 00:29

    You'll want to listen for escape's keyCode (27) from the React SyntheticKeyBoardEvent onKeyDown:

    const EscapeListen = React.createClass({
      handleKeyDown: function(e) {
        if (e.keyCode === 27) {
          console.log('You pressed the escape key!')
        }
      },
    
      render: function() {
        return (
          
        )
      }
    })
    

    Brad Colthurst's CodePen posted in the question's comments is helpful for finding key codes for other keys.

提交回复
热议问题