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

如何在React Native Image主资源加载前显示加载指示器/占位图且避免重复加载

React Native 实现图片加载前的占位/加载指示器(无外部库)

解决defaultSource导致主图片重复加载的问题,同时保留onLoadEnd事件,可自定义GIF占位或加载指示器,方案如下:

核心思路

通过状态变量手动控制图片加载状态:

  • 初始状态下显示占位内容(GIF/指示器)
  • 主图片加载完成(通过onLoadEnd监听)后,切换显示主图片,隐藏占位

代码实现

import React, { useState } from 'react';
import { View, Image, ActivityIndicator } from 'react-native';

const YourComponent = () => {
  const [isImageLoaded, setIsImageLoaded] = useState(false);
  const baseURL = '你的基础API地址';
  const loadingGif = require('./path/to/loading.gif'); // 本地加载GIF

  return (
    <View style={{ height: 300, width: 300, position: 'relative' }}>
      {/* 加载完成前显示占位内容 */}
      {!isImageLoaded && (
        // 选项1:显示加载GIF
        <Image
          source={loadingGif}
          style={{ height: '100%', width: '100%', resizeMode: 'cover' }}
        />
        // 选项2:显示ActivityIndicator加载指示器
        // <ActivityIndicator 
        //   size="large" 
        //   color="#666" 
        //   style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} 
        // />
      )}

      {/* 主图片:加载完成后显示 */}
      <Image
        source={{ uri: `${baseURL}/api/Images/ResizeImage` }}
        style={{
          height: '100%',
          width: '100%',
          resizeMode: 'cover',
          position: 'absolute',
          top: 0,
          left: 0,
          opacity: isImageLoaded ? 1 : 0,
          transitionProperty: 'opacity',
          transitionDuration: '300ms' // 可选:添加平滑过渡效果
        }}
        onLoadEnd={() => setIsImageLoaded(true)}
      />
    </View>
  );
};

export default YourComponent;

关键说明

  1. 避免重复加载:移除defaultSource,通过状态控制显示逻辑,彻底解决主图片两次请求的问题
  2. 灵活自定义占位:可替换为本地GIF、静态占位图或系统ActivityIndicator
  3. 保留事件监听:正常使用onLoadEnd(或onLoad)监听加载完成状态,可扩展处理加载失败场景
  4. 平滑过渡:通过opacity和过渡动画实现占位到主图的自然切换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:22:07