react中视频定时器的使用

	在实际应用中,我们可能需要在视频播放页面使用定时器,进行数据上报,观察用户的使用习惯进行后续的优化。
	需求:
		1.视频播放开始的时候开启定时器
		2.视频暂停的时候停止计时器
		3.视频播放超过十秒进行弹窗提醒
	实现思路:
		1.通过createRef创建定时器以及video标签的引用来控制定时器与播放器
	代码如下:
import Taro, { Component, Config, createRef } from '@tarojs/taro'
import { View, Text ,Video } from '@tarojs/components'

interface UserProps {
    
}

interface UserState {
    timer:number
}

export default class Test extends Component<UserProps, UserState> {
    
    constructor(props) {
        super(props);
        this.timeRef = createRef<any>();
        this.videoRef = createRef<HTMLVideoElement>();
        this.state = {
            timer: 0 ,
        }
    }

    componentDidMount() {
    
    }
    
    componentDidUpdate() {
    
    }

    componentWillUnmount(){
        const {timeRef} = this;
        if(timeRef && timeRef.current){
            clearInterval(timeRef.current);
        }
    }

    timeRef :any;
    videoRef:any;
    config: Config = {
        navigationBarTitleText: '视频资源练习'
    };

    componentDidHide() {
    
    }

    playHandler=()=>{
        const {timer}= this.state;
        const {videoRef,timeRef} = this;
        if(videoRef && videoRef.current.duration >= timer){
            let i = 0;
            timeRef.current = setInterval(() => {
                i++;
                this.setState({timer:timer+i})
                console.log(timer+i);
                if(timer+i === 10){
                    videoRef.current.pause();
                    Taro.showModal({
                        title:'恭喜你已学习10秒钟',
                        content:'非常棒啊啊啊啊啊啊',
                        success:function(){
                            videoRef.current.play();
                        }
                    })
                }
            }, 1000);
        }else{
            clearInterval(timeRef.current)
        }
    }

    pauseHandler=()=>{
        const {timeRef} = this;
        if(timeRef && timeRef.current){
            clearInterval(timeRef.current);
        }
    }

    initPlay(){
        
    }
    
    render() {
        const { timer } = this.state
        return (
            <View>
                <Text>{timer}</Text>
                <Video src='自己的视频地址' ref={this.videoRef} controls onPlay={this.playHandler} onPause={this.pauseHandler}></Video>
            </View>
        );
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值