javascript - 如何在 ReactJS 中使用 lis 创建播放列表

标签 javascript reactjs filereader

我正在尝试创建一个 UI,允许用户将 mp3 从他们的计算机下载到播放列表。现在我已经得到了歌曲的名称和指向正确歌曲的 li 的 href。但是现在我想知道每次用户单击 li 时如何在音频元素上播放歌曲。现在这是它的样子:

enter image description here

我的状态是这样的:

enter image description here

这是我的代码:

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>
    )
  }
}

关于javascript - 如何在 ReactJS 中使用 lis 创建播放列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59381601/

相关文章:

Android StrictMode 总是提示 FileReader

javascript - 用jquery延迟一个对象的方法

reactjs - 如何在滚动上 react konva 缩放

reactjs - 每次路由更改时,componentDidUpdate 都会调用两次

javascript - JQuery:如何将文件推送到另一个输入数组值?

java - 如何实现自定义 FilterReader?

javascript - 为什么在运行时 key 未知时我应该使用 Map()?

javascript - 在 JavaScript OnClick 中模拟单击事件会导致错误

javascript - 在 x 轴上带有范围选择器的 d3 条形图(如 dygraphs)

javascript - React 中的闭包