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

问题描述 投票:1回答:1

我正在尝试创建一个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;
javascript reactjs filereader
1个回答
0
投票

我还没有测试过,但是希望您可以在音频标签中添加状态

<audio src={this.state.file}/>

然后单击鼠标后更改状态:

<li onClick={()=>this.setState({file:”mysong.ogg”})}>change song<li>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.