滑动视图组件
render(){
<View style={{flex:1}}>
<ScrollView
horizontal = 'true',
showsHorizontalScrollIndicator = 'true',
showsVerticalScrollIndicator = 'false',
onContentSizeChange ={(contentWidth, contentHeight) = > {'滚动内容的视图发生变化时调用'}},
refreshControl= 'true',
refreshControl = {() => {}}
pagingEnabled = 'true',
……
/>
</View>
}
var Dimensions = require('Dimensions');
var {width} = Dimensions.get('window');
var TimerMixin = require('react-timer-mixin');
……
constructor(props){
super(props);
this.state = {
mixins: [TimerMixin],
duration: 2000,
currentPage: 0
}
}
componentDidMount() {
this.startTimer();
},
render() {
return (
<View style={styles.container}>
<ScrollView style={styles.scrollViewStyle}
ref="scrollView"
horizontal={true}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
onMomentumScrollEnd={(e)=>this.onAnimationEnd(e)}
onScrollBeginDrag={this.onScrollBeginDrag}
onScrollEndDrag={this.onScrollEndDrag}
>
{this.renderAllImages()}
</ScrollView>
<View style={styles.cycleStyle}>
{this.renderAllCycle()}
</View>
</View>
)
},
startTimer() {
var scrollView = this.refs.scrollView;
this.timer = this.setInterval(function() {
var tempPage;
if (this.state.currentPage+1 >=7) {
tempPage = 0;
} else {
tempPage = this.state.currentPage+1;
}
this.setState( {
currentPage: tempPage
});
let offSet = tempPage * width;
scrollView.scrollTo({x: offSet, y: 0, animated: true});
}, this.state.duration);
},
onAnimationEnd(e) {
let offset = e.nativeEvent.contentOffset.x;
let page = Math.floor(offset / width);
this.setState({
currentPage: page
});
},
onScrollBeginDrag() {
this.clearInterval(this.timer);
},
onScrollEndDrag() {
this.startTimer();
},
renderAllImages() {
var imageItems = [];
var imageNames = ['1.jpg', '2.jpg', '3.jpg', '4.jpg','5.jpg', '6.jpg', '7.jpg'];
var colors = ['red', 'blue', 'green', 'purple', 'brown', 'black', 'yellow'];
for (var i=0; i<7; i++) {
imageItems.push(
<Image key={i}
source={{uri: imageNames[i]}}
style={{backgroundColor: colors[i], width: width, height: 300}} />
);}
return imageItems;
},
renderAllCycle() {
var cycleItems = [];
var colorStyle;
for (var i=0; i<7; i++) {
colorStyle = (i==this.state.currentPage) ? {color: 'gray'} : {color: 'white'}
cycleItems.push(
<Text key={i} style={[{fontSize: 30, left: 10}, colorStyle]}>•</Text>)
}
return cycleItems;
}
})
const styles = StyleSheet.create({
container: {
width: width,
height: 300,
backgroundColor: 'green',
},
scrollViewStyle: {
backgroundColor: 'yellow',
width:width,
marginTop: 20
},
cycleStyle: {
backgroundColor: 'rgba(241,241,241,0.5)',
width: width,
height: 30,
position: 'absolute',
bottom: 0,
flexDirection: 'row',
alignItems: 'center'
}
});