reactjs 如何通过在React上使用onKeyDown单击特定按钮来播放音频?

jgzswidk  于 2023-02-22  发布在  React
关注(0)|答案(2)|浏览(209)

我正在做一个滚筒机项目,我没有通过一项任务。该任务是:
当我按下与每个.drum-pad相关联的触发键时,应该触发其子元素中包含的音频剪辑(例如,按下Q键应该触发包含字符串“Q”的drum-pad,按下W键应该触发包含字符串“W”的drum-pad,等等)。
我的代码到目前为止:

class Drumset extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }
  componentDidMount() {
    document.addEventListener("keydown", this.handleKeyPress);
  }

  handleClick = (event) => {
    const audio = event.target.children[0];
    audio.play();
  };

  handleKeyPress = (event) => {
    if (
      event.key === "q" ||
      event.key === "w" ||
      event.key === "e" ||
      event.key === "a" ||
      event.key === "s" ||
      event.key === "d" ||
      event.key === "z" ||
      event.key === "x" ||
      event.key === "c"
    ) {
      const audio = event.target.children[0];
      audio.play;
      console.log("key pressed");
    }
  };

  render() {
    return (
      <div>
        <div id="drum-machine" class="containerx box-middle">
          <div id="display" onKeyDown={this.handleKeyPress}>
            <div class="container">
              <div class="row">
                <div class="col">
                  <button
                    type="button"
                    class="drum-pad"
                    id="Heater-1"
                    onClick={this.handleClick}
                  >
                    Q
                    <audio
                      class="clip"
                      id="Q"
                      src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
                      type="audio/mpeg"
                    ></audio>
                  </button>

我的问题是,每当我按下一个键,handleKeyPress()函数工作,但音频不播放(控制台显示打印)。如何播放音频时,我按下相关的按钮?

f4t66c6m

f4t66c6m1#

问题是这样的:在handleKeyPress处理程序中,const audio = event.target.children[0];不以audio元素为目标。
我已经使用ref在用户点击handleKeyPress中提到的任何键时定位音频。同样,每当我们使用onKeyDown合成事件时,我们必须使用tabIndex={0}。请尝试以下代码:)

import React, { Component } from "react";

export default class DrumSet extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  componentDidMount() {
    document.addEventListener("keydown", this.handleKeyPress);
  }
  handleKeyPress = (event) => {
    console.log(event.key);
    if (
      event.key === "q" ||
      event.key === "w" ||
      event.key === "e" ||
      event.key === "a" ||
      event.key === "s" ||
      event.key === "d" ||
      event.key === "z" ||
      event.key === "x" ||
      event.key === "c"
    ) {
      this.myRef.current.play();
      console.log("key pressed");
    }
  };
  handleClick = (event) => {
    const audio = event.target.children[0];
    audio.play();
  };
  render() {
    return (
      <div>
        <div id="drum-machine" className="containerx box-middle">
          <div id="display" onKeyDown={this.handleKeyPress} tabIndex={0}>
            <div className="container">
              <div className="row">
                <div className="col">
                  <button type="button" className="drum-pad" id="Heater-1">
                    Q
                    <audio
                      className="clip"
                      id="Q"
                      src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
                      type="audio/mpeg"
                      ref={this.myRef}
                    ></audio>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
7uhlpewt

7uhlpewt2#

我设法使它通过测试而不使用onKeyDown属性。我认为解决办法是使用keyCode事件而不是handle keyPress方法中的key事件。请看我对这个问题的解决方案。我希望它能有所帮助,并随时提出任何问题。

`
import React from 'https://esm.sh/react@18.2.0'
import ReactDOM from 'https://esm.sh/react-dom@18.2.0'

常量Map键= { 81:“Q”,87:“W”,69:“E”,65:“A”,83:“S”,68:“D”,90:“Z”,88:“X”,67:“C”};

class DrumMachine extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
    };
    this.handlePlay = this.handlePlay.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }
  componentDidMount() {
    document.addEventListener("keydown", this.handleKeyPress)
  }
 componentWillUnmount() {
   document.removeEventListener("keydown", this.handleKeyPress)
 }
  handlePlay(id, audName) {
    document.getElementById(id).play();
    this.setState({name: audName})
    console.log("clicked")
  }
  handleKeyPress(event) {
    //console.log(event.keyCode);
    let key = mapKeys[event.keyCode];
    key && document.getElementById(key).play()
  }
  render() {
    return (
      <section className="main">
      <div id="drum-machine">
        <div className="pads-div">
          <div 
            className="drum-pad"
            id="heater-1"
            onClick={()=>this.handlePlay("Q", "Heater 1")}
            //onKeyDown={ this.handleKeyPress}
            >Q
            <audio 
              id= "Q"
              src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3" 
            className="clip"
              >audio</audio>
         </div>
          <div 
            className="drum-pad"
            id="heater-2"
            onClick={()=>this.handlePlay("W", "Heater 2")}
            //onKeyDown={this.handleKeyPress}
            //tabIndex={1}
            >W
            <audio 
              id="W"
              src="https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3" 
              className="clip"
              >audio</audio>
          </div>
          <div 
            className="drum-pad"
            id="heater-3"
            onClick={()=>this.handlePlay("E", "Heater 3")}
           // onKeyDown={this.handleKeyPress}
            //tabIndex={2}
            >E
            <audio 
              id="E" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3" 
            className="clip"
              >audio</audio>
          </div>
          <div 
            className="drum-pad"
            id="heater-4"
            onClick={()=>this.handlePlay("A", "Heater 4")}
            //onKeyDown={this.handleKeyPress}
            //tabIndex={3}
            >A
            <audio 
              id="A" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3" 
            className="clip"
              >audio</audio>
          </div>
          <div 
            className="drum-pad"
            id="clap"
            onClick={()=>this.handlePlay("S", "Clap")}
            //onKeyDown={this.handleKeyPress}
            //tabIndex={4}
            >S
            <audio 
              id="S" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3" 
            className="clip"
              >audio</audio>
          </div>
          <div 
            className="drum-pad" 
            id="open-hh"
            onClick={()=>this.handlePlay("D", "Open HH")}
            //onKeyDown={this.handleKeyPress}
            //tabIndex={5}
            >D
            <audio 
              id="D" src="https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3" 
            className="clip"
              >audio</audio>
          </div>
          <div 
            className="drum-pad"
            id="kick-n'-hat"
            onClick={()=>this.handlePlay("Z", "Kick n' Hat")}
            //onKeyDown={this.handleKeyPress}
            //tabIndex={6}
            >Z
            <audio 
              id="Z" src="https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3" 
            className="clip"
              >audio</audio>
          </div>
          <div 
            className="drum-pad"
            id="kick"
            onClick={()=>this.handlePlay("X", "Kick")}
            //onKeyDown={this.handleKeyPress}
            //tabIndex={7}
            >X
            <audio 
              id="X" src="https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3" 
            className="clip"
              >audio</audio>
          </div>
          <div className="drum-pad"
            id="closed-hh"
            onClick={()=>this.handlePlay("C", "Closed HH")}
            //onKeyDown={this.handleKeyPress}
            //tabIndex={8}
            >C
            <audio 
              id="C" src="https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3" 
            className="clip"
              >audio</audio>
          </div>
        </div>
        <div className="display-div">
        <div id="display">
          <h4>{this.state.name}</h4>
        </div>
          <p></p>
        </div>
      </div>
      </section>
    )
  }
}

ReactDOM.render(<DrumMachine />, document.getElementById("root"))`

这是我的代码pend.https://codepen.io/0PENJI/pen/oNPNxgK?editors=1111。你可以跟着我跟进解决方案。谢谢。

相关问题