首页 > 解决方案 > 如何为平面列表中的单个项目设置动画?

问题描述

我如何为 flatlist 中的单个项目设置动画?

在 flatlist 上实现了 onpress 缩放动画,但 onpress 动画应用于 flatlist 中的所有项目。我只想将动画应用于一项。

动画代码在这里

const scaleInAnimated = useRef(new Animated.Value(0)).current;
    const SCALE = {
      getScaleTransformationStyle(animated: Animated.Value, startSize: number = 1, endSize: number = 0.95) {
        const interpolation = animated.interpolate({
          inputRange: [0, 1],
          outputRange: [startSize, endSize],
        });
        return {
          transform: [
            { scale: interpolation },
          ],
        };
      },

     pressInAnimation(animated: Animated.Value, duration: number = 100) {
        animated.setValue(0);
        Animated.timing(animated, {
          toValue: 1,
          duration,
          useNativeDriver: true,
        }).start();
      },
      pressOutAnimation(animated: Animated.Value, duration: number = 500) {
        animated.setValue(1);
        Animated.spring(animated, {
          toValue: 0,
          duration,
          useNativeDriver: true,
        }).start();
      },
    };
    

平面列表代码

<FlatList
        onEndReachedThreshold={1}
        onEndReached={_handleLoadMore}
          data={trending}
          renderItem={({ item,index }) =>(<TouchableOpacity activeOpacity={0.9} onPress={()=>{navigation.navigate('DetailMovie',{id:item.id})}}
            onPressIn={() => {SCALE.pressInAnimation(scaleInAnimated);}}
            onPressOut={() => {SCALE.pressOutAnimation(scaleInAnimated);}}
            style={SCALE.getScaleTransformationStyle(scaleInAnimated)}
            >
              <Animated.View>
                <ImageBackground
                  source={{uri:`${imageurl}${item.poster_path}`}}
                  style={[styles.cardimage]}
                  imageStyle={styles.cardItemImage}>
                    <LinearGradient colors={['transparent','rgba(0,0,0,0.8)']} style={styles.background}>
                        <Text style={styles.cardTitle} numberOfLines={1}>{item.title}{item.name} </Text>
                        <Text style={styles.cardMeta}><MaterialCommunityIcons name='star' size={14} color={colors.yellow}/>{item.vote_average}</Text>
                    </LinearGradient>
                </ImageBackground>
                </Animated.View>
            </TouchableOpacity>)
        }
          keyExtractor={(item) =>item.id.toString()}
          horizontal
          showsHorizontalScrollIndicator={false}
          ListHeaderComponent={Blank}
          ListHeaderComponentStyle={styles.blank}
        />

怎么修 ?谢谢

标签: react-nativereact-native-flatlistreact-animated

解决方案


推荐阅读