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

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

    If you're looking for a document-level key event handling, then binding it during componentDidMount is the best way (as shown by Brad Colthurst's codepen example):

    class ActionPanel extends React.Component {
      constructor(props){
        super(props);
        this.escFunction = this.escFunction.bind(this);
      }
      escFunction(event){
        if(event.keyCode === 27) {
          //Do whatever when esc is pressed
        }
      }
      componentDidMount(){
        document.addEventListener("keydown", this.escFunction, false);
      }
      componentWillUnmount(){
        document.removeEventListener("keydown", this.escFunction, false);
      }
      render(){
        return (   
          
        )
      }
    }
    

    Note that you should make sure to remove the key event listener on unmount to prevent potential errors and memory leaks.

    EDIT: If you are using hooks, you can use this useEffect structure to produce a similar effect:

    const ActionPanel = (props) => {
      const escFunction = useCallback((event) => {
        if(event.keyCode === 27) {
          //Do whatever when esc is pressed
        }
      }, []);
    
      useEffect(() => {
        document.addEventListener("keydown", escFunction, false);
    
        return () => {
          document.removeEventListener("keydown", escFunction, false);
        };
      }, []);
    
      return (   
        
      )
    };
    

提交回复
热议问题