FlatList onEndReached事件在React-Native上的ScrollView中不起作用

时间:2020-01-13 08:09:52

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

我将通过使用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)}
      />
    );
  }

2 个答案:

答案 0 :(得分:2)

这不是 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上为父动画添加滚动事件。 希望对您有所帮助。

答案 1 :(得分:0)

替换此行:

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

与此:

onEndReachedThreshold={0.5}

它将起作用。