最近在做一个基于RN的App,需要用到播放视频的组件,官方没有,只能从第三方寻找,react-native-video首当其冲。
之前感觉这个组件还是蛮好用的,但是后来出现 需要在一个使用react-native-video的地方,再放一个倒计时组件的场景,倒计时首先采用的是react-native-sk-countdown,本来这两个组件若是不放在一起,都运行良好,但是结果放在同一个组件中,react-native-sk-countdown总是会因为视频的播放进度而导致只能在1s内循环,无法倒计时到0,捣鼓了一个晚上,还是没能找出头绪来,干脆自己动手做一个得了。
当然,我只是想要一个最简单的倒计时组件而已,react-native-sk-countdown其实还是有些重型了,而我自定义的这个倒计时组件自然比不上的。
组件的代码如下:
class MyCountTime extends Component{
constructor(props) {
super(props);
let timeLeft=this.props.timeLeft>0 ? this.props.timeLeft:5
let width=this.props.width || 60
let height=this.props.height || 32
let color=this.props.color || '#fff'
let fontSize=this.props.fontSize || 22
let fontWeight=this.props.fontWeight || '600'
let borderColor=this.props.borderColor || '#ee735c'
let borderWidth=this.props.borderWidth || 1
let borderRadius=this.props.borderRadius || 4
let backgroundColor=this.props.backgroundColor || '#ee735c'
this.afterEnd=this.props.afterEnd || this._afterEnd
this.style=this.props.style || this.countTextStyle
this.state={
timeLeft:timeLeft
}
this.countTextStyle={
textAlign:'center',
color:color,
fontSize:fontSize,
fontWeight:fontWeight
}
this.countViewStyle={
backgroundColor:backgroundColor,
alignItems:'center',
borderColor:borderColor,
borderWidth:borderWidth,
borderRadius:borderRadius,
width:width,
height:height
}
}
countdownfn(timeLeft,callback){
if(timeLeft>0){
let that=this
let interval=setInterval(function(){
if(that.state.timeLeft<1){
clearInterval(interval)
callback()
}else{
let totalTime=that.state.timeLeft
that.setState({
timeLeft:totalTime-1
})
}
},1000)
}
}
_afterEnd(){
console.log('------------time over');
}
componentDidMount(){
let time=this.state.timeLeft
let afterEnd=this.afterEnd
this.countdownfn(time,afterEnd)
}
render(){
return (
<View>
<Text style={this.style}>{this.state.timeLeft}</Text>
</View>
)
}
}
用法如下:
<MyCountTime
timeLeft={5} //倒计时的总时间
width={100}
height={60}
color={'#fff'}
fontSize={24}
fontWeight={'normal'}
borderColor={'transparent'}
borderWidth={1}
borderRadius={2}
let backgroundColor={'#ee735c'}
afterEnd={()=>{console.log('afterEnd fn')}}
style={}/>
倒计时功能其实就是利用了setInterval()
这个函数,而到倒计时完成后的动作,则是通过一个回调来完成
相比于react-native-video来说,这个组件很简单,不过也具备倒计时功能、也能自定义样式,同时也有倒计时完成后的回调函数,三者都可以自定义,一般的场景基本上算是能够满足了。
除此之外,由于组件本身代码的逻辑简单,所以若是用的不顺手了完全可以自己动手再改改,也可以说是高度定制化了。