如何在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;
关键说明
- 避免重复加载:移除
defaultSource,通过状态控制显示逻辑,彻底解决主图片两次请求的问题 - 灵活自定义占位:可替换为本地GIF、静态占位图或系统
ActivityIndicator - 保留事件监听:正常使用
onLoadEnd(或onLoad)监听加载完成状态,可扩展处理加载失败场景 - 平滑过渡:通过
opacity和过渡动画实现占位到主图的自然切换
内容的提问来源于stack exchange,提问作者Roman Uk
相关产品推荐
相关产品推荐

