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

前端 未结 5 920
梦如初夏
梦如初夏 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:16

    Another way to accomplish this in a functional component, is to use useEffect and useFunction, like this:

    import React, { useEffect } from 'react';
    
    const App = () => {
    
    
      useEffect(() => {
        const handleEsc = (event) => {
           if (event.keyCode === 27) {
            console.log('Close')
          }
        };
        window.addEventListener('keydown', handleEsc);
    
        return () => {
          window.removeEventListener('keydown', handleEsc);
        };
      }, []);
    
      return(

    Press ESC to console log "Close"

    ); }

    Instead of console.log, you can use useState to trigger something.

提交回复
热议问题