我正在尝试创建一个UI,以允许用户将mp3从他们的计算机下载到播放列表。现在,我已经获得了歌曲的名称和指向正确歌曲的li的href。但是现在我想知道每次用户单击li时如何在音频元素上播放歌曲。现在,它是这样的:
我的状态如下:
这是我的代码:
class DownloadTest extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.inputRef = React.createRef();
this.state = {
files: []
};
}
handleClick = event => {
// Helper code to read file and return promise
const readFile = (file) => {
const fileList = [];
const fileReader = new FileReader();
// create the promise and return it
return new Promise((resolve, reject) => {
// if file reader has an error, report it
fileReader.onerror = (error) => {
reject({ error })
}
// if success, resolve the promise
fileReader.onload = (e) => {
resolve({
name: file.name,
link: e.target.result
})
}
// start reading the file
fileReader.readAsDataURL(file);
})
}
// create all the file reader promises
// create an array from the files list and use map to generate
// an array of promises
const allReaders = Array.from(event.target.files).map(readFile)
// Now handle the array of promises we just created
Promise.all(allReaders)
.then(fileList => {
console.log(fileList)
// set the state that we have all the files
this.setState({ files: fileList });
})
.catch(error => {
console.error(error)
});
}
render() {
console.log(this.state);
return (
<div className="downloadMusic">
<div className="input">
<input
onChange={this.handleClick}
id="upload-file"
className="inputName"
type="file"
multiple
ref={this.inputRef}
/>
</div>
<div className="audio-player">
<audio
src="my_audio_file.ogg"
autoPlay
controls
/>
</div>
<div>
<ul ref={this.ulRef}>
{this.state.files.map((file, index) => (
<li key={index}>
<a href={file.link}>{file.name}</a>
</li>
))}
</ul>
</div>
</div>
);
}
}
export default DownloadTest;
答案 0 :(得分:1)
更新后的答案,经过测试可以正常工作。您可以使用组件状态来更改音频元素的来源。
import React from "react";
import { render } from "react-dom";
import Joy from "./joy.wav"
import Alive from "./alive1.wav"
class App extends React.Component {
constructor() {
super();
this.state = {
audio: Joy
}
}
render() {
return (
<div>
<button onClick={() => this.setState({ audio: Alive })}>
Change audio
</button>
<audio src={this.state.audio} controls />
</div>
)
}
}