【问题标题】:React Native. trying to load an image from url反应原生。尝试从 url 加载图像
【发布时间】:2020-07-03 09:05:10
【问题描述】:

我已设法将网络上的图片加载到我的应用中,但有一个问题...

我有一些关于食物的本地数据。每个食物都有一个食物标题和一个在线图片的网址。

这是位于我的 foodComponent 中的 Image 组件。

<Image style={styles.cardImg} source={{uri:image}} />

image 是一个 url 的字符串,作为 prop 传递给这个 foodComponent。

它再次起作用,但我的问题是图像需要时间来加载。 我如何才能在 foodItem 组件接收/加载图像后才渲染它?

我知道承诺,但我不知道如何在这种情况下使用它。

这是我的整个 foodItem 组件:

export default function FoodItemTouchable(props){
    return(
        <View style={styles.container}>
            <View style={styles.card}>

                <View style={styles.cardHeader}>
                    <Text style={styles.text}>{props.item.title}</Text>
                </View>

                <Break/>

                <CardImage image={props.item.url}/>

            </View>
        </View>
    )
}


function Break() {
    return(
        <View style={{alignItems:'center'}}>
            <View style={styles.break}>
            </View>
        </View>
    )
}

function CardImage({image}){
    return(
        <View style={{padding:10,width:'100%'}}>
            <Image
                style={styles.cardImg}
                source={{uri:image}}
              />
        </View>
    )
}

CardImage 是图像被渲染的地方。 其余组件首先呈现,但 CardImage 延迟,因为它正在加载图像。

如果我能以某种方式将图像加载到主组件中的变量中, 然后检查一下,是 image===null 吗?返回空 以便组件仅在图像准备好时呈现。

【问题讨论】:

    标签: image react-native


    【解决方案1】:

    你试过这样吗?

    {
    props.item.url
    &&
    <CardImage image={props.item.url}/>
    }
    

    【讨论】:

    • 是的。我认为问题是, props.item.url 确实存在,但只是作为一个字符串,一旦程序继续,cardImage 最终开始获取图像。并需要几秒钟来加载它。我在想,如果我将图像转换为 base64 会怎样,现在我可以将图像作为字符串保存到 FoodItem 组件中的 const 中。也可以传递给图像,它应该立即渲染它?
    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多