如何获取滚动视图索引

kir*_*imi 1 react-native react-native-scrollview

我正在对我scrollview的.slideimageBackground

我用来pagingEnabled滑动图像。index但是有没有办法让我每次刷卡时都能得到号码?

我正在使用滚动视图,如下面的代码。添加pagingEnabled将使滚动视图像 a 一样工作swiper,但我不知道如何获取index.

<ScrollView horizontal={true} pagingEnabled={true}>
            {this.createScrollImageSources(this.state.image)}
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 7

您可以将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>
Run Code Online (Sandbox Code Playgroud)

滚动处理

  handleOnScroll(event){
    //calculate screenIndex by contentOffset and screen width
    console.log('currentScreenIndex', parseInt(event.nativeEvent.contentOffset.x/Dimensions.get('window').width));
  }
Run Code Online (Sandbox Code Playgroud)

工作演示

https://snack.expo.io/HyxzFr2HxU