【问题标题】:React Native Scroll View Question (keep track of full page scroll loaction)React Native Scrollview Question(跟踪整页滚动位置)
【发布时间】:2020-08-09 05:13:29
【问题描述】:

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

我知道屏幕尺寸,并假设我是否可以从视图中当前查看的图像中获取内容偏移量或类似的东西除以屏幕尺寸可以让我知道我正在查看的数组中的图像at 来执行其余的功能。

不幸的是,我不知道如何做到这一点,下面的代码提供了一些上下文。

        <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>

提前致谢, 克里斯。

【问题讨论】:

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


    【解决方案1】:

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

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

    setSelectedIndex 是您应该创建的函数。

    【讨论】:

    • 一旦我开始了,我会尝试一下,干杯
    • 所以我正在玩这个解决方案,我猜测它需要进行大量计算才能确定,因为 snap 值不是给我的,它是给我的最终阻力值,但是有时它可以向后滚动快照或向前滚动快照,而您并不真正知道它的走向,因为该值只是告诉您您抬起手指的位置。
    • 将 'onScrollEndDrag' 与 'onMomentumScrollEnd' 交换。让我知道它是否有效,以便我编辑我的答案(为后代;)
    • 刚要通过这个离子,我使用 onMomentumScrollEnd 方法的计算要好得多,所以我建议更改为 onMomentumScrollEnd 而不是 dragEnd
    【解决方案2】:

    为了给这个问题添加更多的结论,这就是我所做的

      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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2019-07-16
      • 2018-04-09
      • 1970-01-01
      • 2019-07-18
      • 2022-12-22
      • 1970-01-01
      相关资源
      最近更新 更多