【问题标题】:scrollToIndex() is not a functionscrollToIndex() 不是函数
【发布时间】:2019-12-24 00:06:40
【问题描述】:

我目前有一个地图和一个轮播(类似于FlatList),我希望能够使用FlatListscrollToIndex 方法捕捉到数组中的某个项目。问题是当我采用基于ScrollViewreact-native-snap-carousel 库时,我失去了使用scrollToIndex 方法的能力。 FlatList 滚动到某个索引的能力非常好。

我使用的是功能组件,所以我使用的是useRef 钩子:

    const flatListRef = useRef()
    const handleMarker = index => {
        flatListRef.current.scrollToIndex({ index, animated: true })
    }

我在我的地图上使用react-native-maps,上面的handleMarker 是为了当用户点击地图上的标记时,轮播会捕捉到相关项目:

<Marker
    key={marker.id}
    coordinate={{ latitude: marker.latitude, longitude: marker.longitude }}
    onPress={() => handleMarker(index)}
    ref={markerRef[index]}
>
</Marker>

下面是替换FlatList的轮播:

<Carousel
    data={items}
    renderItem={({ item }) => <Item item={item}/>}
    horizontal={true}
    ref={flatListRef}
    sliderWidth={width}
    sliderHeight={100}
    itemWidth={140}
    itemHeight={100}
/>

如果没有scrollToIndex,我如何实现这一点?

【问题讨论】:

    标签: javascript ios react-native carousel react-native-flatlist


    【解决方案1】:

    尝试使用提供的方法来代替

    const handleMarker = index => {
      flatListRef.current.snapToItem(index);    
    }
    

    参考:https://github.com/archriss/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md#available-methods

    【讨论】:

    • 截至 2022 年 3 月:flatListRef.snapToItem(index);
    猜你喜欢
    • 2020-04-06
    • 2019-02-17
    • 1970-01-01
    • 2017-04-26
    • 2018-09-01
    • 2021-07-04
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多