【问题标题】:How to handle dynamic require images react native如何处理动态需求图像反应原生
【发布时间】:2020-12-01 05:59:26
【问题描述】:
  1. 我使用 multer 将图像保存到 MongoDb 到我本地静态文件夹中的路径 /uploads。

  2. 当我获取图像时从数据库中获取的对象如下所示:

      Array [
    Object {
    "_id": "5fc4581a1b858e93a65136e7",
    "desc": "19",
    "image": "uploads/a2.jpg",
     },
     Object {
    "_id": "5fc4584a873e544138a10a33",
    "desc": "19",
    "image": "uploads/a2.jpg",
    },
    ]
    
  3. 现在我想用 desc 和 image 显示数组,所以我定义了一个平面列表并尝试这样做:

            <FlatList
            numColumns={numColumns}
            data={s}
            renderItem={({ item, index }) => (
                console.log("http://localhost:8080/" + item.image),
                (
                    <View style={styles.imagecontainer}>
                        <Text>{item.desc}</Text>
                        {Object.keys(s).length === 0 ? null : (
                            <Image style={styles.image} source= 
       {require(`../../server/${item.image}`)} />/////////here is the problem
                        )}
                    </View>
                )
            )}
            keyExtractor={(item, index) => index.toString()}
        />
    
  • 现在我明白 require 应该只获取静态字符串而不是变量,
  • 问题是如何处理这个问题以根据数组动态显示图像和描述?

我在互联网上阅读了很多,但没有找到答案... 我需要以某种方式转换我得到的对象并将给我“uploads/a2.jpg”的图像道具替换为 {require(../../server/**here to put the image for each object**) 但我找不到这样做的方法。

【问题讨论】:

    标签: reactjs mongodb react-native multer mern


    【解决方案1】:

    我遇到了同样的问题,我发现它的唯一方法是保存 require() 函数返回的图像 ID。

    console.log(require("image path"));
    // return a number for example 5 
    

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多