我有一个React组件,当您单击按钮时可以播放/暂停音频.效果很好,我一次在页面上渲染了其中的5个.但是,如果您单击一个播放,然后单击另一个播放,则两个音频都在播放,这不是很好.这是我的组件代码:
import React from 'react';
import playIcon from './images/play.png';
import pauseIcon from './images/pause.png';
class Music extends React.Component {
constructor(props) {
super(props);
this.state = { 'play': false };
this.url = props.src;
this.audio = new Audio(this.url);
this.audio.preload = 'none';
this.togglePlay = this.togglePlay.bind(this);
}
togglePlay() {
this.setState({'play': !this.state.play}, () => {
this.state.play ? this.audio.play() : this.audio.pause();
});
}
componentWillUnmount () {
this.audio.pause();
}
render() {
return (
<div style={this.props.style} className={this.props.className}>
{this.state.play
? <button className="audio-button" aria-label="Pause" onClick={this.togglePlay}><img src={pauseIcon} width="34" height="34" alt="Pause"></img></button>
: <button className="audio-button" aria-label="Play" onClick={this.togglePlay}><img src={playIcon} width="34" height="34" alt="Play"></img></button>}
</div>
);
}
}
export default Music;
我已经做了一些环顾,一个潜在的解决方案是使用redux或其他状态管理库.我想避免这种情况,因为在此站点中我不需要这样做.我已经研究了事件侦听器(即solution proposed here),但是当我执行document.getElementsByTagName(‘audio’)时,我得到了一个空的HTMLCollection. This solution更近了,但我无法弥合jQuery中的实现与React中所使用的实现之间的差距.
有没有办法识别正在播放的音频并在播放新音频之前从React Component暂停它?任何和所有建议表示赞赏.
解决方法:
import React from 'react';
import audio1 from './audio1.mp3';
import audio2 from './audio2.mp3';
class AudioList extends React.Component {
constructor (props) {
super(props);
this.audios = props.list.map(audio => new Audio(audio));
}
getCurrentAudio () {
return this.audios.find(audio => false === audio.paused);
}
toggle (nextAudio) {
const currentAudio = this.getCurrentAudio();
if (currentAudio && currentAudio !== nextAudio) {
currentAudio.pause();
}
nextAudio.paused ? nextAudio.play() : nextAudio.pause();
}
render () {
return (
<div>
{ this.audios.map((audio, index) =>
<button onClick={() => this.toggle(audio) }>
PLAY AUDIO { index }
</button>
) }
</div>
)
}
}
export default () => <AudioList list={[ audio1, audio2 ]} />;
PS:新的Audio(url)返回HTMLAudioElement.