【问题标题】:How can I use default image if Image url gives 404 error in react native?如果 Image url 在 react native 中出现 404 错误,我该如何使用默认图像?
【发布时间】:2021-07-22 08:47:04
【问题描述】:

如果图像 URL 出现 404 错误,我想加载默认图像。我在图像道具中尝试了 onError() 但它不起作用。

<Image
              onError={() => {
                setError(true);
              }}
              source={{
                uri: error
                  ? imageUrl
                  : "https://logodownload.org/wp-content/uploads/2019/07/udemy-logo-5.png",
              }}
              style={{
                height: 50,
                width: "100%",
                alignItems: "center",
                justifyContent: "center",
              }}
              resizeMode="cover"
            />


我该怎么做?

【问题讨论】:

  • @Horst 我猜这只适用于 ios 而不是 android。
  • 它在发布模式下工作。
  • 但是,在文档中,写着“加载图像源时显示的静态图像”。它只会在加载时显示图像,如果加载完成并且图像出现错误怎么办
  • 一开始就使用静态法师。直到成功获取图像。

标签: javascript reactjs react-native react-hooks react-image


【解决方案1】:

您可以在图像中使用 defaultSource 和默认图像,当提供的 imageUrl 加载失败时会显示默认图像

var defaultImage = yourDefaultImageURl 

在你的形象中

    <Image
    defaultSource={defaultImage}
    source={{uri: imageUrl}}
       style={{
            height: 50,
            width: "100%",
            alignItems: "center",
            justifyContent: "center",
          }}
   resizeMode="cover"
   />

【讨论】:

    【解决方案2】:

    在这种情况下,如何将默认网址置于错误中

     onError={() => {       
     setImageUrl('https://logodownload.org/wpcontent/uploads/2019/07/udemy-logo-5.png');
              }}
    

    在源码中

           source={{uri:imageUrl}}
    

    【讨论】:

    • 如果一张图片加载失败,这将设置所有图片的 URL。
    • 根据提出的问题,我理解它可用于单个图像,然后效果很好。您是否在其他地方加载相同的 imageUrl?
    • 是的,单张图片就可以了。但我正在从服务器获取图像。
    • 在这种情况下,您可以为每个 imageUrls 维护各自的 id 和 flag 并相应地维护状态。这样做有助于刷新和加载已获取的 imageUrls 以及错误状态的图像。
    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2018-08-25
    • 2017-12-26
    • 2016-07-30
    • 2021-09-18
    相关资源
    最近更新 更多