0

对于这个问题我的完整的源代码被公布为世博会的应用程序:https://exp.host/@kevinoldlifeway/swipe-scrollview-of-webviews以及在Github上https://github.com/kevinold/swipe-scrollview-of-webviews的水平“粘性”中心元素反应原住民的ListView

我建立一个书鉴于本机作出反应。使用ScrollView,我想左右滑动浏览可能有几百到几千个标题的页面。

既然是这样的话,我的目标是只有数据的最小量,使得用户可以在页面之间轻扫,眼看着马上上一页和下一页。

我加载一个3元素的数组像这样:

[Previous, Current, Next] 

这将处于通过终极版更新(不是在这里用来保持简单),并会重新渲染和调整名单。

我的目标是我的ScrollView始终是“中心”的“当前”页面上。

滚动到上一页和下一页的页面由handleScroll方法处理,该方法加载相应的预先计算数组,以便当前页面保持焦点,但上一页和下一页(屏幕外)适当更新。

handleScroll (event) { 
    //const x = event.nativeEvent.contentOffset.x; 

    const { activeIndex, scrollTimes } = this.state; 

    const windowWidth = Dimensions.get('window').width; 
    const eventWidth = event.nativeEvent.contentSize.width; 
    const offset = event.nativeEvent.contentOffset.x; 
    console.log('event width: ', eventWidth); 
    console.log('event offset: ', offset); 

    console.log('scrollTimes: ', scrollTimes); 
    //if (scrollTimes <= 1) return; 

    if (windowWidth + offset >= eventWidth) { 
     //ScrollEnd, do sth... 
     console.log('scrollEnd right (nextPage)', offset); 
     const nextIndex = activeIndex + 1; 
     console.log('nextIndex: ', nextIndex); 

    // Load next page 
    this.loadMore() 

    } else if (windowWidth - offset <= eventWidth) { 
     //ScrollEnd, do sth... 
     console.log('scrollEnd left (prevPage)', offset); 

    // Load prev page 
    this.loadPrev() 
    } 

    this.setState({ scrollTimes: scrollTimes + 1 }); 
} 

我试图用平衡的组合 “当前” 页数:ScrollView

而且

componentDidMount() { 
    // Attempt to keep "center" element in array as focused "screen" in the horizontal list view 
    this.scrollView.scrollTo({ x: width, y: 0, animated: false }); 
} 

contentOffset={{ x: width, y: 0 }}我也试着scrollTo在回拨后this.setState,但一直没有任何运气。

我想知道如果这个“定心”,可以通过使用Animated完成。

回答

1

我给了这个镜头,但我不完全确定我理解了这个问题,而且我不确定这会如何保持。

基本上我只是简化了handleScroll函数。首先检查我们是否在滚动完成,如果是这样,确定我们在该屏幕上登陆时是“上一个”屏幕还是“下一个” - 如果它已经是中间屏幕,则不执行任何操作。

我想在你的代码的问题是,它会触发和负载数据,如果它是中间的屏幕,不只是第一个或最后一个。因此每次转换都会触发两次。

下面是我认为会为你工作的handleScroll。

handleScroll (event) { 
    const offset = event.nativeEvent.contentOffset.x; 
    const mod = offset % width; 

    if (mod === 0) { // only transition on scroll complete 
    if (offset === width * 2) { // last screen 
     console.log('load more') 
     this.loadMore(); 
     this.scrollView.scrollTo({ x: width, y: 0, animated: false }); 
    } else if (offset !== width) { // first screen 
     console.log('load prev') 
     this.loadPrev(); 
     this.scrollView.scrollTo({ x: width, y: 0, animated: false }); 
    } 
    } 
} 

Snack演示它。