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

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

    For a reusable React hook solution

    import React, { useEffect } from 'react';
    
    const useEscape = (onEscape) => {
        useEffect(() => {
            const handleEsc = (event) => {
                if (event.keyCode === 27) 
                    onEscape();
            };
            window.addEventListener('keydown', handleEsc);
    
            return () => {
                window.removeEventListener('keydown', handleEsc);
            };
        }, []);
    }
    
    export default useEscape
    

    Usage:

    const [isOpen, setIsOpen] = useState(false);
    useEscape(() => setIsOpen(false))
    

提交回复
热议问题