遇到了关于this的坑
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Image,
ScrollView
} from 'react-native';
var dimensions=require('Dimensions')
var datas=require('./1.json');
var {width, height}=dimensions.get('window')
var TimerMixin = require('react-timer-mixin');
export default class ScrollViewComment extends Component<{}> {
//注册计时器
mixins: [TimerMixin]
constructor(props) {
super(props)
this.state={
currentPage:0
}
this.onScrollBeginDrag = this.onScrollBeginDrag.bind(this);
this.onScrollEndDrag=this.onScrollEndDrag.bind(this)
}
//设置默认值
static defaultProps={
period:1000 //定时器的间隔时间
}
//当render完成后进行初始化定时器
componentDidMount() {
this.startTime();
}
//开启定时器
startTime(){
this.timers=setInterval(()=>{
//每隔一秒钟进行一次操作
var scrollView=this.refs.scrollview;
var size =datas.length;
var currentPages=0;
if (this.state.currentPage + 1>=size) {
currentPages=0;
}else {
currentPages=this.state.currentPage+1;
}
this.setState({
currentPage:currentPages
})
///让图片滚动起来
var offX=this.state.currentPage*width;
scrollView.scrollResponderScrollTo({
x:offX,
y:0,
animated:true //是否有动画
})
},this.props.period)
}
/*开始拖动的时候*/
onScrollBeginDrag(){
//停止定时器
clearInterval(this.timers);
}
onScrollEndDrag(){
//当开始拖拽的时候
this.startTime()
}
render() {
return (
<View style={styles.container}>
<ScrollView
ref="scrollview"
horizontal={true}/*是否水平*/
alwaysBounceHorizontal={true}/*是否水平有弹滑的效果*/
pagingEnabled={true} //是否自动点击分页
showsHorizontalScrollIndicator={false}/*是否显示水平滚动条*/
onMomentumScrollEnd={(e)=>this.onAnimationEnd(e)}/*当开始滚动的时候*/
onScrollBeginDrag ={this.onScrollBeginDrag}/*当开始拖动的时候调用*/
onScrollEndDrag ={this.onScrollEndDrag}/*当停止拖拽的时候*/
>
{this.getScrollviews()}
</ScrollView>
{/*设置指示器*/}
<View style={styles.pageViewStyle}>
{/*返回圆点的指示器*/}
{this.getPagePoint()}
</View>
</View>
);
}
getScrollviews(){
var arrays=[];
for(var i=0;i<datas.length;i++)
{
var data=datas[i];
arrays.push(
<View key={i} >
<Image style={{width:width,height: height/3*2 }}
source={{uri:data.instrument}}/>
</View>
)
}
return arrays;
}
getPagePoint(){
var arrays=[];
var colorStyle;
for(var i=0;i<datas.length;i++)
{
colorStyle=(this.state.currentPage==i)?{color:'red', fontSize:50}:{color:'white',fontSize:25};
var data=datas[i];
arrays.push(
<View key={i} style={styles.pointStyle} >
<Text style={[colorStyle]}>•</Text>
</View>
)
}
return arrays;
}
/*每一帧结束的时候调用*/
onAnimationEnd(e){
var offSetX = e.nativeEvent.contentOffset.x;
//当前的页数
var currentPage= Math.round(offSetX/width);
//更新指示器,绘制ui
this.setState({
currentPage:currentPage
});
}
}
const styles=StyleSheet.create({
pageViewStyle:{
width:width,
height:25,
backgroundColor:'rgba(0,0,0,0.3)',
position:'absolute',
bottom:0,
flexDirection:'row',
alignItems:'center',
justifyContent:'center'
},
pointStyle:{
marginRight:10
}
})
网友评论