You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

滚动FlatList时为每个卡片添加ActivityIndicator以正常显示图片

FlatList滚动时卡片加载优化:添加ActivityIndicator并修复白块/透明度问题

核心修改思路

针对滚动时卡片加载出现的白块、透明背景问题,我们需要在卡片组件中跟踪图片加载状态,用ActivityIndicator作为加载占位,并通过固定容器背景色消除视觉异常。

修改后的MovieCardFlatlist.tsx代码

import { useState } from 'react';
import { Pressable, Animated, Image, ActivityIndicator, View, StyleSheet } from 'react-native';
import { useNavigation, StackNavigationProp } from '@react-navigation/native';
import { RootStackParams } from '../types'; // 请根据项目路径调整

type Props = {
  movie: { id: number; poster_path: string };
  height?: number;
  width?: number;
};

export const MovieCardFlatList = ({ movie, height = 420, width = 300 }: Props) => {
  const uri = `https://image.tmdb.org/t/p/w500${movie.poster_path}`;
  const navigation = useNavigation<StackNavigationProp<RootStackParams>>();
  // 跟踪图片加载状态
  const [isLoading, setIsLoading] = useState(true);

  return (
    <Pressable
      onPress={() => navigation.navigate('DetailsScreen', movie)}
      style={{
        width,
        height,
        marginHorizontal: 2,
        paddingBottom: 20,
        paddingHorizontal: 7
      }}
    >
      <Animated.View style={styles.imageContainer}>
        {/* 加载状态显示ActivityIndicator */}
        {isLoading && (
          <View style={[styles.loadingContainer, { width, height }]}>
            <ActivityIndicator size="large" color="#ffffff" />
          </View>
        )}
        <Image
          source={{ uri }}
          style={[styles.image, isLoading && { opacity: 0 }]}
          onLoadStart={() => setIsLoading(true)}
          onLoadEnd={() => setIsLoading(false)}
          resizeMode="cover"
        />
      </Animated.View>
    </Pressable>
  );
};

const styles = StyleSheet.create({
  imageContainer: {
    width: '100%',
    height: '100%',
    backgroundColor: '#2d2d2d', // 固定深色背景,消除加载时的透明/白块
    borderRadius: 8,
    overflow: 'hidden',
  },
  loadingContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2d2d2d', // 和容器背景一致
  },
  image: {
    width: '100%',
    height: '100%',
  },
});

关键修改点说明

  • 加载状态管理:通过useState创建isLoading状态,监听Image的onLoadStart和onLoadEnd事件切换状态,确保加载过程中显示指示器。
  • 消除白块/透明问题:给imageContainer设置固定深色背景,替代默认的透明/白色背景,加载时不会出现突兀的视觉空白。
  • 图片过渡优化:加载时将图片透明度设为0,避免未加载完成的模糊图片闪烁,加载完成后自动显示清晰图片。
  • 居中加载指示器:通过绝对定位让ActivityIndicator在卡片中央显示,明确告知用户内容正在加载。

额外建议

如果需要更高效的图片缓存和加载性能,可以考虑使用第三方图片库优化加载逻辑,减少加载延迟和重复请求,进一步提升滚动时的流畅度。

内容的提问来源于stack exchange,提问作者GabVlado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:17:42