React Native Maps FlatList scrollToIndex()不是函数/ undefined

问题描述 投票:0回答:1

我正在使用顶部有动画FlatList的React Native地图,当我按下地图标记时,我希望列表滚动到该特定索引。但是当我尝试这样做时,我得到了这个错误_this.flatListRef.scrollToIndex is not a function. '_this.flatListRef.scrollToIndex' is undefined

我的代码的基础知识看起来像这样......

const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);

export default Map extends component {

  scrollToCard = index => {
    this.flatListRef.scrollToIndex({index})
  }

  render() {

    const { allProperties } = this.props;

    <MapView
       ref={map => this.map = map}
       style={styles.map}
       initialRegion={{
          latitude: 35.2271,
          longitude: -80.8431,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.421
          }}
       >

       {allProperties && allProperties.map((property, index) => (
         <Marker
           coordinate={property.coordinates}
           title={property.propertyName}
           pinColor={theme.COLOR_GREEN}
           key={property.id}
           onPress={() => this.scrollToCard(index)}
         />
       ))}

       </MapView>

         {allProperties &&
            <AnimatedFlatList
               ref={ref => {this.flatListRef = ref }}
               data={allProperties}
               getItemLayout={(data, index) => (
                  {length: CARD_WITH_MARGIN, offset: CARD_WITH_MARGIN * index, index}
               )}
               initialNumToRender={2}
               horizontal
               scrollEventThrottle={1}
               showsHorizontalScrollIndicator={false}
               snapToInterval={CARD_WITH_MARGIN}
               onScroll={Animated.event(
                  [
                     {
                        nativeEvent: {
                           contentOffset: {
                             x: this.animation
                           },
                        },
                      },
                  ],
                  { useNativeDriver: true }
                    )}
               style={styles.scrollView}
               contentContainerStyle={styles.scrollContainer}
               renderItem={this._renderItem}
               keyExtractor={item => item.id}
             />
         }
  }

}

主要看起来我的flatListRef的引用由于某种原因是未定义的。至少这是我的理论,但我不知道为什么。

谁能发现我在这里做错了什么?

如果有帮助,allProperties是从graphql查询返回的数据。

javascript react-native react-native-flatlist react-native-maps
1个回答
3
投票

如果有人发现这个帖子并且遇到同样的问题(或者在我忘记的时候对我来说),我找到了答案here...

看起来,为了使用Ref和私有变量,就像我在组件上面创建的动画一样,你需要在调用它时使用getNode()

例如,在我的scrollToCard()函数中它应该做了以下...

this.flatListRef.getNode().scrollToIndex({index})

© www.soinside.com 2019 - 2025. All rights reserved.