单击按钮时需要播放音频文件的帮助(React)

这是我正在编写的代码。这是一个鼓机项目。我已成功创建按钮,我需要帮助来在单击按钮后播放音频文件。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;

任何帮助,将不胜感激。


慕雪6442864
浏览 80回答 1
1回答

慕桂英3389331

在单击处理程序时使用它:soundOn = info => {&nbsp; var audio = new Audio(info.src);&nbsp; audio.play();}并将其放入onClick道具中:<button&nbsp; // you need a key prop&nbsp; key={info.idnum}&nbsp; className=“drum-pad”&nbsp; id={info[“idnum”]}&nbsp; onClick={() => this.soundOn(info)}>&nbsp; {info.id}</button>此外,如果预加载音频文件,您可能会获得更好的用户体验:const sounds = [&nbsp; {&nbsp; &nbsp; idnum: “1”,&nbsp; &nbsp; id: “Q”,&nbsp; &nbsp; src: “1.html”,&nbsp; &nbsp; audio: new Audio("1.html"),&nbsp; },]并使用这个处理程序:soundOn = info => {&nbsp; info.audio.play();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5