简体   繁体   中英

React onkeypress event to run a function

I'm new at react & coding. I want to run a function if space & up arrow pressed. i want to run my jump() function

const jump = () => {
    if (onJump == false){
        $("#dino").animate({top:'-=60%'}, 300);
        $("#dino").animate({top:'+=60%'}, 300);
        onJump=true;
        setTimeout(function() {
          onJump=false;
        },600)
    }
}

i already try several codes but none of them are working.

If you don't need to focus on any element and want to listen to keyboard events, you need to add listener to the window object. Here is the solution for spacebar key be pressed down and key up event of up key

import React, { useRef } from 'react';

function KeyUpHandler() {

    const keysPressedDown = useRef({});

    useEffect(() => {
        window.addEventListener("keydown",
            (event) => {
                // space
                if (event.keyCode == 32) {
                    keysPressedDown.current[event.keyCode] = true;
                }
                // up
                if (event.keyCode == 38) {
                    keysPressedDown.current[event.keyCode] = true;
                }
            }, false);
        window.addEventListener("keyup",
            event => {
                // space
                if (event.keyCode == 32) {
                    keysPressedDown.current[event.keyCode] = false;
                }
                if (keysPressedDown.current[32] && event.keyCode == 38 &&
                    keysPressedDown.current[38]) {
                    // call your function here 
                    console.log(' space and up ');
                }
                // up
                if (event.keyCode == 38) {
                    keysPressedDown.current[event.keyCode] = false;
                }
            }, false);
    }, []);

    return <></>

}
const handlePress = e => {
 if(e.key === 'Enter') { 
  jump()
 }
}

<button onKeyPress={handlePress}>Press Enter</button>

See key codes https://keycode.info/

Html elements div, h1, p, nav, ... don't receive events like keypress, focus, blur, ... by default. You can enable it specifying tabindex :

<div tabIndex={-1} onKeyPress={...}></div> // better to use <= 0

The above handleFunction runs if your cursor is over that element but if you want it to fire independent to cursors position, you should add eventlistener to window:

window.addEventListener('keypress', e => {
 if(e.key === 'Enter'){
  console.log('You pressed Enter')
 }
})

EDIT:

use keydown event otherwise arrow keys don't work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM