這是我正在編寫的代碼。這是一個鼓機項目。我已成功創建按鈕,我需要幫助來在單擊按鈕后播放音頻文件。src 將填充音頻文件的鏈接,我的項目告訴我將一個元素放入按鈕元素內。這是代碼:import React from “react”;import ReactDom from “react-dom”;const sounds = [{idnum: “1”,id: “Q”,src: “1.html”,},{idnum: “2”,id: “W”,src: “2.html”,},{idnum: “3”,id: “E”,src: “3.html”,},{idnum: “4”,id: “A”,src: “4.html”,},{idnum: “5”,id: “S”,src: “5.html”,},{idnum: “6”,id: “D”,src: “6.html”,},{idnum: “7”,id: “Z”,src: “7.html”,},{idnum: “8”,id: “X”,src: “8.html”,},{idnum: “9”,id: “C”,src: “9.html”,},];class Button extends React.Component {constructor(props) {super(props);this.state = {audioSource: “not clicked”,};this.soundOn = this.soundOn.bind(this);}/* soundOn() {return sounds.src.play();} */// I know the above method will not work. I just had it to check if my buttons were working.render() {const buttonData = sounds.map((info) => (<button className=“drum-pad” id={info[“idnum”]} onClick={this.soundOn}>{info[“id”]}));return buttonData;}}export default Button;任何幫助,將不勝感激。
1 回答

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
在單擊處理程序時使用它:
soundOn = info => {
var audio = new Audio(info.src);
audio.play();
}
并將其放入onClick道具中:
<button
// you need a key prop
key={info.idnum}
className=“drum-pad”
id={info[“idnum”]}
onClick={() => this.soundOn(info)}
>
{info.id}
</button>
此外,如果預加載音頻文件,您可能會獲得更好的用戶體驗:
const sounds = [
{
idnum: “1”,
id: “Q”,
src: “1.html”,
audio: new Audio("1.html"),
},
]
并使用這個處理程序:
soundOn = info => {
info.audio.play();
}
- 1 回答
- 0 關注
- 196 瀏覽
添加回答
舉報
0/150
提交
取消