我正在为 React 项目使用 React Player npm install 。视频播放器处于模式中。当模式关闭时如何停止播放?是否可以在
ReactPlayer.stop()
函数中添加 ReactPlayer.pause()
或 hideModal
类型的功能?
<Modal show={this.state.show} handleClose={this.hideModal} >
<ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' width='100%'
height='100%' />
</Modal>
如果
this.state.show
返回布尔值(真/假),你可以通过这样的状态来控制它:
<ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' playing={this.state.show} width='100%' height='100%' />
viciousP 有正确的答案,但我认为值得展示完整的代码示例,以便其他人可以准确地了解其工作原理。
使用状态挂钩
import React, { useState } from 'react';
import ReactPlayer from 'react-player';
function Video() {
const video_source = "https://vimeo.com/blahblah";
function close_video() {
setPlay(false)
}
const [play, setPlay] = useState(true);
return(
<ReactPlayer id="video" url={video_source} playing={play}/>
)
}
export default Video;
现在您可以通过调用
close_video()
以编程方式停止视频播放
对我来说这个例子效果更好,关键点是一起使用 onPlay、onPause 和playing prop
function VideoModal({ isShow, onClose, source }: any) {
const [isPlaying, setPlaying] = useState(false)
return (
<AppModal
onClose={() => {
setPlaying(false)
onClose()
}}
isShow={isShow}
>
<ReactPlayer
playing={isPlaying}
height='100%'
width="100%"
controls={true}
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
url={source}
/>
</AppModal>
)
}
这解决了问题:根据真/假状态值安装和卸载模态
例如:而不是
<Modal show={this.state.show} handleClose={this.hideModal} >
<ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' width='100%'
height='100%' />
</Modal>
这样做
{ (this.state.show) ? <Modal show={this.state.show} handleClose={this.hideModal} >
<ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' width='100%'
height='100%' />
</Modal>
: null }
通过这种方式,您可以安装和卸载模态框,并在模态框关闭时停止视频播放。