【问题标题】:How to get scrollview index如何获取滚动视图索引
【发布时间】:2020-01-10 07:25:18
【问题描述】:
我正在使用 react-native scrollview 到 slide 我的 imageBackground。
我正在使用pagingEnabled 滑动图像。但是有没有一种方法可以让我在刷卡时获得index 的号码?
我正在使用滚动视图,如下面的代码。添加pagingEnabled 将使滚动视图像swiper 一样工作,但我不知道如何获得index。
<ScrollView horizontal={true} pagingEnabled={true}>
{this.createScrollImageSources(this.state.image)}
</ScrollView>
【问题讨论】:
标签:
react-native
react-native-scrollview
【解决方案1】:
您可以使用onScroll 方法和Dimensions 模块来计算currentScreenIndex。
示例:
渲染
<View style={styles.container}>
<ScrollView pagingEnabled horizontal style={{flex: 1}} onScroll={(e)=>this.handleOnScroll(e)} scrollEventThrottle={5}>
<View style={{width: SCREEN_WIDTH, backgroundColor: 'yellow'}} />
<View style={{width: SCREEN_WIDTH, backgroundColor: 'red'}} />
<View style={{width: SCREEN_WIDTH, backgroundColor: 'green'}} />
</ScrollView>
</View>
handleOnScroll
handleOnScroll(event){
//calculate screenIndex by contentOffset and screen width
console.log('currentScreenIndex', parseInt(event.nativeEvent.contentOffset.x/Dimensions.get('window').width));
}
工作演示
https://snack.expo.io/HyxzFr2HxU
【解决方案2】:
我所做的是使用onScroll 属性来检查水平滚动视图的当前偏移量。然后将当前偏移量与您的设备宽度进行比较。
试试:
<ScrollView onScroll={this.handleScroll} />
然后:
handleScroll: function(event: Object) {
console.log(event.nativeEvent.contentOffset.x);
},