【发布时间】:2018-06-02 00:41:13
【问题描述】:
我有一个 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 组件暂停它?任何和所有的建议表示赞赏。
【问题讨论】:
-
为什么音频不是组件?
标签: javascript reactjs audio