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

前端 未结 5 923
梦如初夏
梦如初夏 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条回答
  •  长发绾君心
    2021-01-30 00:28

    React uses SyntheticKeyboardEvent to wrap native browser event and this Synthetic event provides named key attribute,
    which you can use like this:

    handleOnKeyDown = (e) => {
      if (['Enter', 'ArrowRight', 'Tab'].includes(e.key)) {
        // select item
        e.preventDefault();
      } else if (e.key === 'ArrowUp') {
        // go to top item
        e.preventDefault();
      } else if (e.key === 'ArrowDown') {
        // go to bottom item
        e.preventDefault();
      } else if (e.key === 'Escape') {
        // escape
        e.preventDefault();
      }
    };
    

提交回复
热议问题