javascript - 如何在 ReactJS 中使用 lis 创建播放列表
问题描述
我正在尝试创建一个 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;
解决方案
更新的答案,测试和工作。您可以使用组件状态来更改音频元素源。
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>
)
}
}
推荐阅读
- java - 获取有条件地加入休眠或将实体设计更改为有条件地获取子项?
- python - 如何使用 Consul Agent CLI 创建新的 KV 条目,但前提是它们尚不存在?
- r - 在 R 中使用 min-max 变换时更好地处理 0?
- multithreading - 在并行化循环中正确使用 private 和 firstprivate (intel fortran)
- openstack - Microstack 托管实例中没有可用的互联网
- regex-greedy - 排除资产正则表达式
- c# - Lock 和 SemaphoreSlim 与 async/await 的使用差异
- tags - 按标签过滤显示所有页面而不是标记页面
- javascript - 用于在网上商店抓取一些相关信息的 Chrome 扩展程序
- excel - 在 MS Excel 中,如何将 mm.ss 转换为 mm:ss?