在 React Native 中获取 ScrollView 的当前滚动位置 [英] Get current scroll position of ScrollView in React Native

查看:42
本文介绍了在 React Native 中获取 ScrollView 的当前滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 React Native 中获取当前滚动位置或 组件的当前页面?

Is it possible to get the current scroll position, or the current page of a <ScrollView> component in React Native?

比如:

<ScrollView
  horizontal={true}
  pagingEnabled={true}
  onScrollAnimationEnd={() => { 
      // get this scrollview's current page or x/y scroll position
  }}>
  this.state.data.map(function(e, i) { 
      <ImageCt key={i}></ImageCt> 
  })
</ScrollView>

推荐答案

尝试.

<ScrollView onScroll={this.handleScroll} />

然后:

handleScroll: function(event: Object) {
 console.log(event.nativeEvent.contentOffset.y);
},

在另一种情况下,假设您还想实现分页指标,你会想通过这样做走得更远:

In another context, let's say you also want to implement a pagination indicator, you'll want to go further by doing this:

<ScrollView
     onScroll={Animated.event([{ nativeEvent: { contentOffset: { x: 
     scrollX } } }], {listener: (event) => handleScroll(event)})}
     scrollEventThrottle={16}
>
   ...some content
</ScrollView>

其中 scrollX 将是一个动画值,您可以将其用于分页,而您的 handleScroll 函数可以采用以下形式:

where scrollX would be an animated value you can use for you pagination and your handleScroll function can take the form:

  const handleScroll = (event) => {
    const positionX = event.nativeEvent.contentOffset.x;
    const positionY = event.nativeEvent.contentOffset.y;
  };

这篇关于在 React Native 中获取 ScrollView 的当前滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆