参照了这篇文章自己写了一个做备份http://www.jianshu.com/p/84faf0154d5
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
ScrollView
} from 'react-native';
var Images = require('./images.json');
import Dimensions from 'Dimensions';
import TimerMixin from 'react-timer-mixin';
var width = Dimensions.get('window').width;
var ScrollViewProject = React.createClass({
mixins:[TimerMixin],
getInitialState() {
return {
currentPage:0
}
},
render() {
return(
<View style={styles.container}>
{/*轮播*/}
<ScrollView ref='scrollView'
horizontal={true}
showsHorizontalScrollIndicator={false}
pagingEnabled={true}
onScroll={(e)=>this.changeIndicators(e)}
onScrollBeginDrag={this.onScrollBeginDrag}
onScrollEndDrag={this.onScrollEndDrag}
>
{this.renderAllImage()}
</ScrollView>
{/*轮播指示器*/}
<View style={styles.indicators}>
{this.renderIndicator()}
</View>
</View>
);
},
componentDidMount() {
// this.setInterval(
// ()=>console.log('testTimeout'),1000
// );
// 开启定时器
this.startTimer();
},
renderAllImage() {
var allImgs = [];
var imgData = Images.data;
var srcs = [
require("./imgs/a.jpg"),
require("./imgs/b.jpg"),
require("./imgs/c.jpg"),
require("./imgs/d.jpg"),
require("./imgs/e.jpg")
];
for(let i=0;i<imgData.length;i++) {
allImgs.push(
<Image key={i} source={srcs[i]}
style={{width:width,height:180}}
/>
)
}
return allImgs;
},
renderIndicator() {
var indicators = [];
for(let i=0;i<5;i++) {
let style = (i==this.state.currentPage)?{color:'#ffff00'}:{color:'#ffffff'}
indicators.push(
<Text key={i} style={[{fontSize:30,marginLeft:5},style]}>•</Text>
)
}
return indicators;
},
changeIndicators(e) {
var offsetX = e.nativeEvent.contentOffset.x;
this.setState({
currentPage:Math.floor(offsetX/width)
})
},
// 设置轮播自动滚动
startTimer() {
// 1. 拿到scrollView
var scrollView = this.refs.scrollView;
// 2. 添加定时器
this.timer = this.setInterval(()=>{
// console.log('haha');
// 2.1 设置圆点
var activePage;
// 2.2 判断
if(this.state.currentPage+1 >=5) activePage=0;
else activePage=this.state.currentPage+1;
// 2.3 更新状态
this.setState({
currentPage:activePage
})
// 2.4 让scroll滚动起来
var offsetX = activePage * width;
scrollView.scrollResponderScrollTo({x:offsetX,y:0,animated:true});
},1000);
},
// 拖动轮播时停止定时器
onScrollBeginDrag() {
this.clearInterval(this.timer);
},
// 拖动结束后打开定时器
onScrollEndDrag() {
this.startTimer();
}
});
const styles = StyleSheet.create({
container: {
// flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
// marginTop:20
},
indicators: {
flexDirection:'row',
backgroundColor:'rgba(0,0,0,0.1)',
height:30,
width:width,
alignItems:'center',
marginTop:-30
}
});
AppRegistry.registerComponent('ScrollViewProject', () => ScrollViewProject);