为DIV处理`onKeyup'

发布于 2025-02-04 14:33:19 字数 243 浏览 6 评论 0原文

我想处理键盘上的键以运行一个功能,我想做的是:

<div className="playerContainer" onKeyUp={gameState.toggleCP}></div>

但是没有好处(DIV在整个页面上缩放),我也试图将处理程序添加到默认应用程序类组件,该怎么办?

I want to handle a key clicked on the keyboard to run a function, I'm trying to do:

<div className="playerContainer" onKeyUp={gameState.toggleCP}></div>

but there is no benefit (the div is scaled on the whole page), also I tried to add the handler to the default App class component, what to do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对风讲故事 2025-02-11 14:33:20

据我了解,问题是gameState.togglecp未在事件上调用。
为了使事件处理程序在元素上调用 - 元素必须焦点。

TL:DR;将侦听器添加到文档

如果要处理键>键事件,无论焦点是哪个元素 - 在React App App组件中,请执行以下操作:

import { useCallback, useEffect } from "react";

const gameState = {
  toggleCP: () => {
    // your function instructions
  },
};

export function MyComponent() {
  const handleKeyUp = useCallback(
    (event) => {
      gameState.toggleCP();
    },
    [gameState.toggleCP]
  );

  useEffect(() => {
    document.addEventListener("keyup", handleKeyUp);
    return () => {
      document.removeEventListener("keyup", handleKeyUp);
    };
  }, [handleKeyUp]);

  return <div className="playerContainer"></div>;
}

祝你好运弗伦!

as i understand, the problem is that gameState.toggleCP is not being called on keyup event.
keyup in order for event handler will be called on an element — element must be in focus.

TL:DR; add keyup listener onto the document

if you want to handle keyup event no matter which element is in focus — within React app component do the following:

import { useCallback, useEffect } from "react";

const gameState = {
  toggleCP: () => {
    // your function instructions
  },
};

export function MyComponent() {
  const handleKeyUp = useCallback(
    (event) => {
      gameState.toggleCP();
    },
    [gameState.toggleCP]
  );

  useEffect(() => {
    document.addEventListener("keyup", handleKeyUp);
    return () => {
      document.removeEventListener("keyup", handleKeyUp);
    };
  }, [handleKeyUp]);

  return <div className="playerContainer"></div>;
}

good luck fren!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文