在实际应用中,我们可能需要在视频播放页面使用定时器,进行数据上报,观察用户的使用习惯进行后续的优化。
需求:
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>
);
}
}