- 这是一个是一个可滚动的容器,可以再其中放入多个组件和视图,不仅可以竖直滚动,也可以水平滚动
- 现在通过一个轮播图来初步了解一下他的属性和方法,项目的github地址:https://github.com/Yangyifan584921/ScrollViewDemo,记得点星星哦
export default class reactDemo extends React.Component{ constructor(props){ super(props); this.state={ currentIndex:0, imgDate:[ "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1586207542,1126066039&fm=27&gp=0.jpg", "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=382424164,2265057143&fm=27&gp=0.jpg", "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1474506808,2225489807&fm=27&gp=0.jpg", "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1820830892,319341373&fm=27&gp=0.jpg" ] }; this.carousel=this.carousel.bind(this); this.dragStart=this.dragStart.bind(this); this.dragEnd=this.dragEnd.bind(this); this.onAnnotationEnd=this.onAnnotationEnd.bind(this) } componentDidMount(){ this.carousel(); } doClick(index){ clearInterval(this.carouselTimer); this.setState({currentIndex:index},()=>{ let ScrollView=this.refs.scrollView; const currentX=this.state.currentIndex*Dimensions.get('window').width; ScrollView.scrollResponderScrollTo({x:currentX,animated:true}) }); } //滑动时清除定时器 dragStart(){ clearInterval(this.carouselTimer) } //停止滑动时触发定时器 dragEnd(){ this.carousel() } carousel(){ let ScrollView=this.refs.scrollView; const timer=4000; let currentIndex=this.state.currentIndex; this.carouselTimer=setInterval(()=>{ currentIndex===this.state.imgDate.length-1?currentIndex=0:currentIndex++; this.setState({ currentIndex:currentIndex },()=>{ const currentX=currentIndex*Dimensions.get('window').width; ScrollView.scrollResponderScrollTo({x:currentX,animated:true}) }) },timer) } onAnnotationEnd(e){ const offsetX=e.nativeEvent.contentOffset.x; const currentIndex=offsetX/Dimensions.get('window').width; this.setState({ currentIndex:currentIndex }) } render(){ const {imgDate,currentIndex}=this.state; const screenWidth=Dimensions.get('window').width; const imgDataList=imgDate.map((ele,index)=>{ return( <Image key={index} style={{screenWidth,height:240}} source={{url:ele}}></Image> ) }); const doList=imgDate.map((ele,index)=>{ return( <Text onPress={this.doClick.bind(this,index)} key={index} style={[styles.dotStyle,{backgroundColor:currentIndex===index?'red':'fff'}]}></Text> ) }) return( <View> <Text style={styles.myTitleStyle}>ScrollView轮播图</Text> <ScrollView ref="scrollView" horizontal={true} showsHorizontalScrollIndicator={true} pagingEnabled={true} onScrollBeginDrag={this.dragStart} onScrollEndDrag={this.dragEnd} onMomentumScrollEnd={this.onAnnotationEnd} > {imgDataList} </ScrollView> <View style={styles.dotView}>{doList}</View> </View> ) } }
> 常用方法:
> - onMomentumScrollBegin:函数->当视图滚动时
> - onMomentumScrollEnd:函数->当视图停止滚动时
> 常用属性:
属性 | 作用 |
showsHorizontalScrollIndicator | 控制是否显示水平方向的滚动条 |
showsVerticalScrollIndicator | 控制是否显示垂直方向的滚动条 |
scrollEnabled | 控制控件是否能滚动 |
contentOffSet | 监控目前滚动的位置 |
bounces | 控制控件遇到边框是否反弹 |
pagingEnabled | 控制控件是否整页翻动 |
horizontal | 为true时水平滚动,为false时数值滚动 |