反应本机滚动视图问题(跟踪整页滚动位置)

时间:2020-08-09 05:13:29

标签: javascript reactjs react-native react-native-android scrollview

我有一个滚动视图,其中包含一张覆盖整个屏幕的图像。屏幕底部有两个按钮,这些按钮可让您下载图像或将其设置为墙纸。我遇到的问题是我不知道单击按钮时在水平滚动视图中正在查看哪个图像。

我了解屏幕尺寸,并假设是否可以从视图中当前查看的图像除以屏幕尺寸得到内容偏移量或类似内容,可以让我知道我要查找的数组中的图像即可执行其余功能。

不幸的是,我不知道如何在下面的代码中给出一些背景信息。

        <ScrollView 
          horizontal
          decelerationRate={0}
          snapToInterval={width}
          snapToAlignment={"center"}
          style={{ height: height }}
        >
          {
            availibleBackgrounds.map(element => (
              <Image
                style={{ width: width, height: height, justifyContent: 'flex-end', alignItems: 'center' }}
                source={{
                  uri: element
                }}
              />
            ))
          }
        </ScrollView>

预先感谢, 克里斯。

2 个答案:

答案 0 :(得分:1)

您需要获取内容的偏移量,并且可以通过在ScrollView中添加以下内容来实现:

onMomentumScrollEnd={event => setSelectedIndex(event.nativeEvent.contentOffset.x/width)}

setSelectedIndex 是您应该创建的函数。

答案 1 :(得分:1)

要对此问题添加更多的内容,这是我所做的

  calculateCurrentIndex(position) {
    this.setState({ 
      selectedIndex: {
        current: Math.ceil((position / width).toFixed(2)),
      } 
    });
  }

----------------------------------------

        <ScrollView 
          horizontal
          decelerationRate={0}
          snapToInterval={width}
          snapToAlignment={"center"}
          style={{ height: height }}
          onMomentumScrollEnd={event => this.calculateCurrentIndex(event.nativeEvent.contentOffset.x)}
          showsHorizontalScrollIndicator={false}
        >
          {
            availibleBackgrounds.map((element, index) => (
              <Image
                key={index}
                style={{ width: width, height: height, justifyContent: 'flex-end', alignItems: 'center' }}
                source={{
                  uri: element
                }}
              />
            ))
          }
        </ScrollView>