【问题标题】:Dynamically changing Image URLs in React Native在 React Native 中动态更改图像 URL
【发布时间】:2015-12-10 10:35:20
【问题描述】:

我正在尝试动态设置图像 URL。图像在本地存储,它们的位置路径在 JSON 文件中。

JSON 文件

{
  "total": 2,
  "categories": [
    {
      "id": "cat1",
      "name": "Burgers",
      "itemCount": 10,
      "images":{
        "main":"./../images/items/Burgers.jpg"
      }
    },
    {
      "id": "cat2",
      "name": "Pizzas",
      "itemCount": 5,
      "images":{
        "main":"./../images/items/Pizzas.jpg"
      }
    }
  ]
}

代码

renderItem: function (item) {
    var imageURL = require(item.images.main);
    return (
        <View style={styles.mainContainer}>
            <Image source={imageURL} style={styles.image}>
                <Text style={styles.textMain}>{item.name}</Text>
            </Image>
        </View>
    );
}

这会产生以下错误。

2015-12-10 16:02:45.295 [错误][tid:com.facebook.React.RCTExceptionsManagerQueue] 未处理的 JS 异常:需要未知模块“./../images/items/Burger.jpg ”。如果您确定模块在那里,请尝试重新启动打包程序。

但如果我将 var imageURL = require(item.images.main); 替换为 var imageURL = require("./.. /images/items/Pizzas.jpg");它完美地显示了图像。

这是什么原因造成的?如何正确执行?

【问题讨论】:

  • 异常抱怨Burger.jpg 丢失。当您对字符串 Pizzas.jpg 进行硬编码时,它可以工作。你确定Burger.jpg 不只是丢失了吗?

标签: image react-native


【解决方案1】:

使用 require(PATH) 方法实际上使打包程序在打包过程中尝试解析图像,如果仅查看变量,它就无法做到这一点。我会尝试做:

<Image source={{uri: image.images.main}} />

【讨论】:

  • 我认为这不再有效。我现在正在我的应用程序中执行此操作。我没有收到任何错误,但我的图像没有显示。为什么显示来自 api 的图像这么难?!
  • 如果您从 url 加载,您需要指定尺寸。
【解决方案2】:

在使用之前我们需要require 图片。

类似的东西;

const image = require("../../assets/someImage.png");

&lt;Image source={image} /&gt;

这件事对我有用。

【讨论】:

  • 如何将它从 require 转换为 uri?
  • @LuvnishMonga 你可以这样做。 跨度>
猜你喜欢
  • 2023-01-03
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多