0

我在表格的每一行都有一个音频播放器。单击时,音频播放。这里的问题是用户可以通过单击每一行来同时播放多个音频。如果正在播放音频并且用户单击另一行的音频,则正在播放的音频必须暂停并且新选择的音频应该开始播放。我试图更新isPlaying每一行的状态,但无法实现我想要的。请让我知道如何使它工作。这是我到目前为止所尝试的:

员工.js

class Employee extends Component<Props, State> {

  render() {
   const employees = this.props.employees;
   return(
    <div>
     <table>
      {employees && employees.map((emp, index) => this.renderEmp(emp, index))}
    </table>
   </div>
  );
}

renderEmp(emp, i) {
 emp.playing = false;
 return (
  <tr key={emp.id}>
    <td>
      <EmpPlayer emp={emp} employees={this.state.employees} key={i}/>
    </td>
  </tr>);
  }
 }

EmpPlayer.js

import React, { Component } from 'react';
import Sound from 'react-sound';
import { ProgressBar } from 'react-player-controls';

type Props = {
 emp: emp,
 employees: employees,
};

class EmpPlayer extends Component<Props, State> {
 toggle;

 constructor(props: Props) {
  super(props);
  this.state = {
   status: Sound.status.PAUSED,
   isPlaying: false
  };
  this.toggle = this.toggle.bind(this);
 }

 toggle() {
  this.setState({ isPlaying: !this.state.isPlaying }, () => {
   this.setPlayStatus();
  });

  if (this.state.status === Sound.status.PLAYING) {
   this.setState({ status: Sound.status.PAUSED, elapseTime: this.state.elapseTime });
  } else {
   this.setState({ status: Sound.status.PLAYING });
  }
}

setPlayStatus () {
 const {employees, emp} = this.props;
 emp.isPlaying = this.state.isPlaying;
 employees.forEach(e => e.playing = e.id === emp.id ? true : false);
}

render() {
 const { emp, employees } = this.props;
 return (
  <div>
    <div onClick={this.toggle}>
       {this.state.status === Sound.status.PLAYING ? (<Icon>pause</Icon>) : (<Icon>play</Icon>)}
    </div>
    <Sound
      url={emp.url}
      playStatus={emp.isPlaying ? this.state.status : Sound.status.PAUSED}
      autoLoad={true}
      onPlaying={this.onPlaying}
      onLoading={this.onLoading}
    />
    <ProgressBar/>
  </div>));
   }
  }
4

0 回答 0