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

React Native 切换Firebase存储图片时如何显示加载图标直到加载完成

实现方案

你只需要新增加载状态、配合Image组件的原生加载回调,再条件渲染ActivityIndicator即可,修改后的完整可运行代码如下:

import React, { useState } from 'react'
import { Image, Text, TouchableOpacity, View, ActivityIndicator } from 'react-native'
import { StyleSheet } from 'react-native'


const data = [
    { url: "https://firebasestorage.googleapis.com/v0/b/asdsa-69cc0.appspot.com/o/1.jpg?alt=media&token=52de8fce-553d-436d-839e-cc3ee0ec29eb" },
    { url: "https://firebasestorage.googleapis.com/v0/b/asdsa-69cc0.appspot.com/o/2.jpg?alt=media&token=0fa85f40-f134-4010-b575-63c1c82e9c81" }
]

const WordPage = () => {
    const [picture, setPicture] = useState(data[0].url)
    // 新增加载状态
    const [isLoading, setIsLoading] = useState(false)

    const nextWord = () => {
        // 点击切换时立刻开启加载状态
        setIsLoading(true)
        setPicture(data[1].url)
    }

    const previousWord = () => {
        setIsLoading(true)
        setPicture(data[0].url)
    }

    return (
        <View style={styles.container}>
            <Image 
                source={{ uri: picture }}
                style={styles.image}
                // 绑定图片加载回调
                onLoadStart={() => setIsLoading(true)}
                onLoadEnd={() => setIsLoading(false)}
            />
            {/* 条件渲染加载图标 */}
            {isLoading && <ActivityIndicator size="large" color="#2196F3" style={styles.loading} />}
            <View style={styles.change}>
                <TouchableOpacity onPress={previousWord}>
                    <Text>
                        Previous
                    </Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={nextWord}>
                    <Text>
                        Next
                    </Text>
                </TouchableOpacity>
            </View>
        </View>
    )
}

export default WordPage

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    image: {
        height: 300,
        width: 300,
        alignSelf: 'center',
        borderRadius: 10,
        resizeMode: 'contain',
        marginTop: 20
    },
    // 加载图标样式,居中覆盖在图片区域
    loading: {
        position: 'absolute',
        alignSelf: 'center',
        marginTop: 170
    },
    change: {
        flexDirection: 'row',
        marginHorizontal: 10,
        marginTop: 20,
        alignItems: 'center',
        justifyContent: 'space-between'
    }
});

核心修改点

  • 从react-native包中导入ActivityIndicator组件
  • 新增isLoading状态变量,控制加载图标的显示隐藏
  • 点击切换图片的回调中先将isLoading设为true,避免切换瞬间的空白感
  • 给Image组件绑定onLoadStart和onLoadEnd回调,自动同步图片加载状态
  • 新增加载图标样式,通过绝对定位让它居中显示在图片区域

可选优化

如果需要处理图片加载失败的场景,可以给Image组件添加onError回调,在回调中关闭加载状态、自定义展示加载失败的提示内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:36:04