繁体   English   中英

反应本地PanResponder以获取当前的scrollView位置

[英]react native PanResponder to get current scrollView position

我想通过使用PanResponder获得我的scrollView的当前y偏移。 这是我到目前为止所做的,但是我找不到找到当前y偏移的方法

componentWillMount() {
   this._panResponder = PanResponder.create({
     onMoveShouldSetPanResponder: (evt, gestureState) => true,
     onPanResponderRelease: (evt, gestureState) => {
      console.log(this.scrollView) //this logs my scrollView
     }
   });
}

<ScrollView ref={(view) => this._scrollView = view} {...this._panResponder.panHandlers}>

假设触摸释放是指一键停止存在的那一刻,则可以使用ScrollVIew的onTouchEnd道具来实现。

我可以通过使用onScroll将偏移量保存在某个位置,然后使用onTouchEnd对该偏移量执行某些操作来做到这一点。

<ScrollView
  onScroll={(event) => {
    this.offsetY = event.nativeEvent.contentOffset.y;
  }}
  onTouchEnd={(event) => {
    console.log('offsetY:', this.offsetY);
    console.log('touch info:', event.nativeEvent);
  }}
>
  {content of the scroll view}
</ScrollView>

如果通过触摸释放表示您应该有零次触摸,则可以通过传递给onTouchEnd的事件来进行确认。

不确定为什么要在panResponder响应中访问y偏移量。 但是有一种方法可以做到。 首先,您需要在组件中定义一个局部变量,例如:

this.currentScrollViewX=0;
this.currentScrollViewY=0;

通常,滚动事件发生时,您可以跟踪scrollView偏移量。 您可以在ScrollView添加道具,例如

<ScrollView onScroll = {e => this._onScroll(e)} ...>
...
</ScrollView>

然后在组件中定义_onScroll方法,在发生滚动时更新currentScrollViewX和currentScrollViewY

_onScroll(e){
    this.currentScrollViewX = e.nativeEvent.contentOffset.x;
    this.currentScrollViewY = e.nativeEvent.contentOffset.x;
}

然后在onPanResponderRelease处理程序中,始终可以通过引用this.currentScrollViewY来获取最新的y偏移量。

如果要使用PanResponder在ScrollView中拖放动画,则在PanResponder拖动和scrollView滚动时会出现一些问题。 更详细的信息在这里https://github.com/facebook/react-native/issues/1046

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM