反应本地。试图从URL加载图像

时间:2020-07-02 22:16:54

标签: image react-native

我设法将网络上的图像加载到我的应用中,但是出现问题...

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

这是我的foodComponent内的Image组件。

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

image是URL的字符串,该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是渲染图像的位置。 其余的Components首先渲染,但是CardImage延迟,因为它正在加载图像。

如果我能以某种方式将图像加载到主组件中的变量中, 然后进行检查,image === null吗?返回null 这样,该组件仅在准备好图像时才呈现。

1 个答案:

答案 0 :(得分:0)

您尝试过这样吗?

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