我在一个音乐播放器应用程序的 PanGestureHandler 中包装了一个 FlatList。PanGestureHandler 允许用户在播放器上向下滑动以将其最小化,Flatlist 显示与用户可以左右滑动的歌曲相对应的图像轮播。这很好用,但是一旦我通过调用 onMomentumScrollEnd=scrollToActiveIndex() 在歌曲组件内的歌曲(FlatList 项目)之间移动后尝试更改状态,PanGestureHandler 就会崩溃。更改状态后,PanGestureHandler 停止响应(无法向下滑动),嵌套的 Flatlist 也不允许在项目之间滑动。请帮助我了解如何解决此问题。谢谢 :)
import React, { useEffect, useRef, useState } from 'react'
import {
Text,
Image,
View,
TouchableOpacity,
TouchableWithoutFeedback,
ImageBackground,
FlatList,
StyleSheet,
Dimensions,
SafeAreaView,
Animated as NativeAnimated
} from 'react-native';
import Animated, { Easing } from 'react-native-reanimated';
import { PanGestureHandler, State } from 'react-native-gesture-handler';
const PlayerWidget = () => {
// to communicate between miniplayer (bottom bar) and song component (image flatlist)
const scrollX = React.useRef( new NativeAnimated.Value(0)).current
const imageRef = React.useRef()
const playerRef = React.useRef()
const [activeIndex, setActiveIndex] = React.useState(0)
const scrollToActiveIndex = (index) => {
setActiveIndex(index)
}
return (
<>
<PanGestureHandler {...gestureHandler}>
<Animated.View style={[styles.container, { transform: [{ translateY }] }]}>
<SongComponent
songList={songList}
scrollX={scrollX}
imageRef={imageRef}
scrollToActiveIndex={scrollToActiveIndex}
/>
</Animated.View>
</PanGestureHandler>
<MiniPlayer
songList={songList}
scrollX={scrollX}
playerRef={playerRef}
activeIndex={activeIndex}
/>
)
}
const SongComponent = ({songList, scrollX, imageRef, scrollToActiveIndex}) => {
return (
<NativeAnimated.FlatList
ref={imageRef}
data={songList}
onScroll={NativeAnimated.event(
[{nativeEvent: {contentOffset: {x:scrollX}}}],
{ useNativeDriver: true }
)}
keyExtractor={( item ) => item.id}
horizontal
pagingEnabled
showsHorizontalScrollIndicator={false}
onMomentumScrollEnd={ev => {
scrollToActiveIndex(Math.floor(ev.nativeEvent.contentOffset.x / width))
}}
renderItem={({ item }) => {
return (
<View style={{width, height: height - TABBAR_HEIGHT}}>
<Image
source={{uri: item.imageUri}}
style={styles.songImage}
/>
</View>
)
}}
/>
)
}