video自定義實現視訊播放功能

Zhencode發表於2020-01-20
import React, {Component} from 'react'
import style from '../style/Video.module.css'
import play from '../../../assets/player/play.png';
import pause from '../../../assets/player/pause.png';

class Video extends Component{
    constructor(props) {
        super(props);
        this.state={
            data:{},
            isPlay: false,
            isShow: true
        }
        this.video=React.createRef()
        this.goPlay=this.goPlay.bind(this)
        this.show_hide=this.show_hide.bind(this)
    }
    render() {
        let isShow=this.state.isShow?style.show:style.hide;
        return(
                <div className={style.container}>
                <div className={style.video_content}>
                    <video src={this.state.data.videoLink}  className={style.video} preload="auto" ref={this.video} poster={this.state.data.coverUri}/>
                    <div className={style.play_img+' '+isShow} onClick={this.show_hide}>
                        <div onClick={this.goPlay} className={style.toggle_img}>
                            <img src={this.state.isPlay? pause:play}/>
                        </div>
                    </div>
                </div>
        )
    }
    show_hide(){
    if(this.state.isPlay&&!this.state.isShow){
        this.setState({
            isShow: true
        },()=>{
            setTimeout(()=>{
                this.setState({
                    isShow: false
                })
            },2000)
        })
    }else if(!this.state.isShow){
        this.setState({
            isShow: true
        })
    }
    this.showID=setInterval(()=>{
        if(!this.state.isPlay&&!this.state.isShow){
            this.setState({
                isShow: true
            })
        }
    })
    }
    goPlay(event){
        if(this.state.isPlay){
           this.video.current.pause()
           this.setState({
               isPlay: false,
               isShow:true
           })
       }else{
           this.video.current.play();
           this.setState({
               isPlay: true
           })
            setTimeout(()=>{
                this.setState({
                    isShow:false
                })
            },2000)
       }
       this.timeId=setInterval(()=>{
           if(this.video.current.ended){
               this.setState({
                   isPlay: false,
                   isShow: true
               })
               clearInterval(this.timeId)
           }
       },1000)
    }
    componentWillUnmount() {
        clearInterval(this.timeId)
        clearInterval(this.showID)
    }
}
const mapPatchToProps=dispatch=>{
    return{
        ...loadingAndToast(dispatch)
    }
}

export default connect(state=>{
    return{
        axios: state.app.http,
        api: state.app.api
    }
},mapPatchToProps)(Video)

相關文章