Javascript 反应:如何播放声音?
有一个Javascript 反应:如何播放声音?,javascript,html,reactjs,Javascript,Html,Reactjs,有一个元素,它有一个子元素。按钮的id被传递到一个playSound()函数中,该函数选择元素的src。但是,当尝试使用sound.play()播放声音时出现错误:sound.play不是函数 单击按钮时如何播放声音?任何帮助都将不胜感激 index.js: import React from 'react'; import ReactDOM from 'react-dom'; //import './style.css'; class DrumMachine extends React.C
元素,它有一个子
元素。按钮的id
被传递到一个playSound()
函数中,该函数选择
元素的src
。但是,当尝试使用sound.play()播放声音时代码>出现错误:sound.play不是函数
单击按钮时如何播放声音?任何帮助都将不胜感激
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
//import './style.css';
class DrumMachine extends React.Component {
constructor(props) {
super(props);
this.state = {
}
this.playSound = this.playSound.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
componentDidMount() {
document.addEventListener('keydown', this.handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyPress);
}
handleKeyPress(e) {
if (e.keyCode === this.props.keyCode) {
this.playSound();
}
}
playSound(id) {
let sound = document.getElementById(id).childNodes[0].src;
console.log(sound)
sound.play();
}
render() {
return (
<div id="drum-machine">
<h1 id="title">Drum Machine</h1>
<div id="display"></div>
<div>
<button id="81" className="drum-pad" onClick={e => this.playSound(e.target.id)}><audio className="clip" id="Q" src='https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'></audio> Q </button>
</div>
</div>
);
}
}
ReactDOM.render(<DrumMachine />, document.getElementById("app"));
从“React”导入React;
从“react dom”导入react dom;
//导入“/style.css”;
类DrumMachine扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
}
this.playSound=this.playSound.bind(this);
this.handleKeyPress=this.handleKeyPress.bind(this);
}
componentDidMount(){
document.addEventListener('keydown',this.handleKeyPress);
}
组件将卸载(){
document.removeEventListener('keydown',this.handleKeyPress);
}
手动按键(e){
if(e.keyCode==this.props.keyCode){
这个。playSound();
}
}
播放声音(id){
let sound=document.getElementById(id).childNodes[0].src;
控制台日志(声音)
声音。播放();
}
render(){
返回(
滚筒机
this.playSound(e.target.id)}>Q
);
}
}
ReactDOM.render(,document.getElementById(“app”);
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Drum Machine</title>
</head>
<body>
<main>
<div id="app"></app>
</main>
</body>
</html>
滚筒机
这是否回答了您的问题?是的,这很有帮助。但是,正确的方法是检索整个
元素并播放它:playSound(id){let sound=document.getElementById(id).childNodes[0];sound.play();}