我正在尝试创建一个反应媒体播放器,我想使用反应媒体事件,但我很困惑如何使用它们。需要一些帮助。
import React, { Component } from 'react';
class Player extends Component {
constructor(props) {
super(props);
}
playOrPause() {
#how should I check here if video is playing or not
}
render() {
return (
<div id="player">
<div id="video-container">
<video key={this.props.video.song} poster={this.props.video.cover_image} controls>
<source src={this.props.video.url} type="audio/mpeg" />
</video>
</div>
<div id="pbar-container">
<div id="pbar"></div>
</div>
<div id="buttons-container">
<img id="play-button" onClick={this.playOrPause} src="images/play.png" alt="play"/>
<div id="time-field">
0:00 / 0:00
</div>
<img id="sound-button" src="images/sound.png" alt="sound"/>
<div id="sbar-container">
<div id="sbar"></div>
</div>
<img id="fullscreen-button" src="images/fullscreen.png" alt="fullscreen"/>
</div>
</div>
);
}
}
export default Player;
以上是我的代码。
我正在尝试播放或暂停视频,但我不知道该怎么做。
使用Javascript我可以执行这些操作,但我想知道如何在React中完成它。
window.addEventListener('load', function() {
video = document.getElementById('video');
playButton = document.getElementById('play-button');
video.load();
video.addEventListener('canplay', function() {
playButton.addEventListener('click', playOrPause, false);
}, false);
}, false);
function playOrPause() {
if (video.paused) {
video.play();
playButton.src = 'images/pause.png';
} else {
video.pause();
playButton.src = 'images/play.png';
}
}
答案 0 :(得分:0)
您可以使用ref函数来获取实际的HTML视频元素。
我已经简化了下面的内容,演示了如何使用ref来获取视频元素,允许您像使用纯JS一样加载/播放/暂停。
class Player extends Component {
state = {
playing: false
}
componentDidMount() {
this.video.load()
}
playOrPause = () => {
// this.video is the element and can be used inside other methods
if (this.video.paused) {
this.video.play()
this.setState(() => ({ playing: true }))
} else {
video.pause()
this.setState(() => ({ playing: false }))
}
}
render() {
// El here is the HTML video element
const ref = (el) => { this.video = el }
const { playing } = this.state;
return (
<div>
<video ref={ref} />
<button onClick={this.playOrPause}>
<img
src={playing ? 'images/pause.png' : 'images/play.png'}
alt={playing ? 'pause' : 'play'}
/>
</button>
</div>
)
}
}