You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React鼓机项目问题:按键触发音效但不显示音效名称

问题分析

你的问题核心在于键盘事件触发时,调用playSound只传递了按键字母(如Q、W),没有传入对应的音效ID(Heater-1、Clap等)。playSound函数需要两个参数:selector(用于获取audio元素)和id(用于设置显示文本),但键盘事件里只传了第一个参数,导致id为undefined,所以setDisplayKey无法收到正确的音效名称。

解决方案

在键盘事件处理函数中,根据按下的按键字母,从sounds数组里匹配对应的音效对象,提取出它的id后,再一起传给playSound函数。

修改后的代码片段

调整useEffect中的键盘事件监听器:

useEffect(() => {
  const myListener = (event) => {
    const pressedKey = event.key.toUpperCase();
    // 从sounds数组匹配对应的音效项
    const matchedSound = sounds.find(sound => sound.key === pressedKey);
    
    if (matchedSound) {
      playSound(matchedSound.key, matchedSound.id);
    }
  };

  if (enabled) {
    document.addEventListener("keydown", myListener);
  }
  
  return () => {
    document.removeEventListener("keydown", myListener);
  };
}, [enabled, sounds]); // 移除eslint-disable,添加sounds作为依赖项

额外优化:把sounds数组用useMemo包裹,避免每次渲染重复创建数组:

import { useMemo } from 'react';

// ...

const sounds = useMemo(() => [
  {
    keyCode: 81,
    key: "Q",
    id: "Heater-1",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3",
  },
  {
    keyCode: 87,
    key: "W",
    id: "Heater-2",
    url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3",
  },
  // 剩余音效对象...
], []);

修改后,键盘触发时就能和鼠标点击行为一致,将对应的音效名称传给setDisplayKey,实现正确的文本显示。

内容的提问来源于stack exchange,提问作者GameSeven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:25:14