简体   繁体   English

反应 onkeypress 事件以运行 function

[英]React onkeypress event to run a function

I'm new at react & coding.我是反应和编码的新手。 I want to run a function if space & up arrow pressed.如果按下空格和向上箭头,我想运行 function。 i want to run my jump() function我想跑我的 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.如果您不需要关注任何元素并想监听键盘事件,则需要在 window object 中添加监听器。 Here is the solution for spacebar key be pressed down and key up event of up key这是按下spacebar键和up键的按键事件的解决方案

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/见钥匙代码https://keycode.info/

Html elements div, h1, p, nav, ... don't receive events like keypress, focus, blur, ... by default. Html 元素div, h1, p, nav, ...默认情况下不接收keypress, focus, blur, ...等事件。 You can enable it specifying tabindex :您可以指定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:如果您的 cursor 超过该元素,则上面的handleFunction运行,但如果您希望它独立于游标 position 触发,您应该将事件监听器添加到 window:

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

EDIT:编辑:

use keydown event otherwise arrow keys don't work使用keydown事件,否则箭头键不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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