【问题标题】:FlatList onEndReached event not working in ScrollView on React-NativeFlatList onEndReached 事件在 React-Native 的 ScrollView 中不起作用
【发布时间】:2020-01-13 08:09:52
【问题描述】:

我将使用 FlatList 显示项目,而 FlatList 组件是 ScrollView 的子组件,因为有一些动画。 OnEndReached 事件在没有父 ScrollView 的情况下工作,但在 ScrollView 中,对我不起作用。 我很确定为什么会这样。 我应该将 ScrollView 用于动画,并使用 FlatList 事件。 有什么解决办法吗?

这是我的 FlatList 代码和结构。

<Animated.ScrollView style={{ flex: 1 }}
  scrollEventThrottle={1}
  onScroll={Animated.event(
    [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
     { useNativeDriver: true }
  )}>

   <ProductSearchResults
      products={this.state.products}
      itemAction={this.navigateToProduct}
      onLoadMore={ async () => {await this.findProducts();}}
      more={this.state.more} />

</Animated.ScrollView>

这是带有 FlatList 的 ProductSearchResults 组件代码。

  render() {
    const { products, setScrolling } = this.props;

    return (
      <FlatList
        contentContainerStyle={styles.container}
        data={products}
        initialNumToRender={1}
        renderItem={this.renderItem}
        keyExtractor={(item, index) => index.toString() }
        removeClippedSubviews={false}
        numColumns={2}
        showsVerticalScrollIndicator={false}
        legacyImplementation={false}
        onEndReached={({ distanceFromEnd }) => {
          console.log('onEndReached:', distanceFromEnd); **// not working**

          if (this.props.more && !this.onEndReachedCalledDuringMomentum)
            this.props.onLoadMore();
        }}
        onEndReachedThreshold={Platform.OS === 'ios' ? 0 : Dimensions.get('window').height / 2}
        onMomentumScrollBegin={() => { this.onEndReachedCalledDuringMomentum = false; }}
        scrollsToTop={false}
        ListFooterComponent={
          this.props.more && <InnerLoading />
        }
        onScrollBeginDrag={() => setScrolling(true)}
      />
    );
  }

【问题讨论】:

标签: react-native scrollview react-native-flatlist


【解决方案1】:

这不是 onEndReached 事件问题。 也许这个事件对你有用,并且会在你的项目上挂载 FlatList 时发生。 有一个问题是您的结构不正确。 要使此事件正常工作,您应该在没有 ScrollView 的情况下更改结构,并且您的代码也可以。 您可以删除 ScrollView 组件。

   <ProductSearchResults
      products={this.state.products}
      itemAction={this.navigateToProduct}
      onLoadMore={ async () => {await this.findProducts();}}
      more={this.state.more}
      onScroll={Animated.event(
        [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }])} 
   />


   <FlatList
    .....
    onScroll={this.props.onScroll}
    .....

   />

和上面的代码一样,你可以在 FlatList 上为父动画添加滚动事件。 希望能帮到你。

【讨论】:

    【解决方案2】:

    替换这一行:

    onEndReachedThreshold={Platform.OS === 'ios' ? 0 : Dimensions.get('window').height / 2}
    

    用这个:

    onEndReachedThreshold={0.5}
    

    它会起作用的。

    【讨论】:

    • 不适合我。同样的问题。该事件在 FlatList 挂载时触发一次。