先看下效果圖
31E51FB3-0839-4FB2-BFB3-BD8EA5312FA4.png
附上代碼 https://github.com/wanwang88/ReactNativeAutoTimerScroll
然后來看下應該怎么布局
render(){
return(
<View style={styles.container}>
<ScrollView
ref='scrollView'
horizontal={true}
showsHorizontalScrollIndicator = {false}
pagingEnabled = {true}
onMomentumScrollEnd = {(e)=>this.onAnimationEnd(e)}
// 開始拖拽
onScrollBeginDrag={this.onScrollBeginDrag}
// 停止拖拽
onScrollEndDrag={this.onScrollEndDrag}
>
{this.renderAllImage()}
</ScrollView>
{/*返回指示器*/}
<View style={styles.pageViewStyle}>
{/*返回5個圓點*/}
{this.renderPageCircle()}
</View>
</View>
)
},
最外面一個view 然后里面一個scrollview顯示圖片和用來顯示指示器的一個view
導入定時器類庫
npm i react-timer-mixin --save
//項目中引入并注冊
//引入:
var TimerMixin = require('react-timer-mixin');
//注冊:
mixins: [TimerMixin],
初始化currentPage 和 duration
//設置固定值
getDefaultProps(){
return{
//每隔1秒刷新一次
duration:1000
}
},
//設置可變的和初始值
getInitialState(){
return {
currentPage:0
}
},
一幀滾動結束方法
onAnimationEnd(e){
// 計算水平方向的偏移量
var offSetX = e.nativeEvent.contentOffset.x;
//當前的頁數
var currentPage= Math.floor(offSetX/width);
//更新指示器,繪制ui
this.setState({
currentPage:currentPage
});
//AlertIOS.alert(" currentPage= " +this.state.currentPage);
}
定時器方法
startTimer(){
var scrollView = this.refs.scrollView;
var imgCount = ImageData.data.length;
//添加定時器
this.timer = this.setInterval(function(){
var activePage = 0;
if((this.state.currentPage+1) >= imgCount){
activePage = 0;
//AlertIOS.alert(" b= " +this.state.currentPage);
}else{
activePage = this.state.currentPage+1;
}
//更新圓點狀態
this.setState({
currentPage:activePage
});
//scrollView 滾動
var scrollOffsetX = activePage * width;
scrollView.scrollResponderScrollTo({x:scrollOffsetX,y:0,animated:false});
},this.props.duration);
},