ReactNative ListView 设置加载数据后的初始滚动位置

ReactNative ListView setting initial scroll position after data loaded

我有一个事件部分,其中的部分标题包含日期。我需要能够跳转到特定日期,以及将初始滚动位置设置为将来的第一个日期。

为了跳转到特定日期,我尝试将它们的 y 位置存储在状态中。

renderSectionHeader= (sectionData, sectionID) => (
      <View
        onLayout={(event) => {
          const { y } = event.nativeEvent.layout;
          const sectionPosition = { [sectionID]: y };
          const sectionPositions = Object.assign({}, this.state.sectionPositions, sectionPosition);
          this.setState({ sectionPositions });
        }}
       ...

我 运行 遇到了这种方法的问题,因为 renderSectionHeader 不会在列表更靠后的元素上调用(由于惰性渲染)。

然后我尝试用数学方法计算位置,但这会导致每个部分的渲染在接近给定日期时显示在屏幕上。

有什么方法可以实现我的需求吗?

相关

https://github.com/facebook/react-native/issues/499

更新

在我的应用程序中,我知道所有行的高度都完全相同。

使用 contentOffset={{ y: offsetY }} 而不是 setScroll 不起作用,因为它仍然需要渲染给定项目之前的所有项目才能工作。

使用 initialListSize={99999999} 确实有效,但会使页面非常慢,我已被警告不要使用它。

更新 2

是否可以将我的初始内容提供给数据源,然后更新数据以在当前屏幕上的元素前后添加额外的项目?

或者是否有我没有找到的库可以满足我的需要?

看起来这可能很快就会被 FlatList 解决,它目前位于 React-Native 存储库的实验文件夹中。

https://github.com/facebook/react-native/blob/a3457486e39dc752799b1103ebe606224a8e8d32/Libraries/Experimental/FlatList.js

Better ListView - FlatList Summary: We really need a better list view - so here it is!

Main changes from existing ListView:

  • Items are "virtualized" to limit memory - that is, items outside of the render window are unmounted and their memory is reclaimed. This means that instance state is not preserved when items scroll out of the render window.
  • No DataSource - just a simple data prop of shape Array<any>. By default, they are expected to be of the shape {key: string} but a custom rowExtractor function can be provided for different shapes, e.g. graphql data where you want to map id to key. Note the underlying VirtualizedList is much more flexible.
  • Fancy scrollTo functionality: scrollToEnd, scrollToIndex, and scrollToItem in addition to the normal scrollToOffset.
  • Built-in pull to refresh support - set set the onRefresh and refreshing props.
  • Rendering additional rows is usually done with low priority, after any interactions/animations complete, unless we're about to run out of rendered content. This should help apps feel more responsive.
  • Component props replace render functions, e.g. ItemComponent: ReactClass<{item: Item, index: number}> replaces renderRow: (...) => React.Element<*>
  • Supports dynamic items automatically by using onLayout, or getItemLayout can be provided for a perf boost and smoother scrollToIndex and scroll bar behavior.
  • Visibility callback replaced with more powerful viewability callback and works in vertical and horizontal mode on at least Android and iOS, but probably other platforms as well. Extra power comes from the viewablePercentThreshold that lets the client decide when an item should be considered viewable.

演示: