在 React Native 中动态加载图像 [英] Dynamically load Images in React Native

查看:84
本文介绍了在 React Native 中动态加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React Native 的半新手,我遇到了一个问题...

Semi-new to React Native and i'm having an issue...

我试图根据变量(存储在 JSON 文件中的 ID)要求本地图像,如果我将图像在线存储在某处并使用道具,我可以实现这一点:source:{uri: 'https://www.domian.com'+this.props.model.id'.png'} 例如,但显然 require 需要只是一个字符串,所以我不能传递一个变量?

I'm trying to require local images based on a variable (an ID stored in a JSON file), I can achieve this if I stored the images online somewhere and used the prop: source:{uri: 'https://www.domian.com'+this.props.model.id'.png'} for example, but obviously require needs just a single string so I can't pass it a variable?

我只想为每个/if 语句使用冗长的语句,但图像名称将有 100 多个选项.这是我宁愿将图像存储在本地的另一个原因.

I would just use a lengthy for each/if statement but there will be 100+ options for the image name. Which is another reason i'd rather have the images stored locally.

我尝试了很多不同的方法,但没有找到任何方法,有什么办法可以解决这个问题吗?

I've been trying a bunch of different ways but haven't found anything, is there any way around this?

推荐答案

以下对我有用:

// our data
// we need to require all images, 
// so that React Native knows about them statically
const items = [
    {
        id: '001',
        image: require('../images/001.jpeg'),
    },
    {
        id: '002',
        image: require('../images/002.jpeg'),
    },
];

// render
items.map( (item) => 
    <Image key={item.id} source={item.image} />
)

注意:这是基于@soutot 的更新答案,但已简化.我认为不需要布尔值.

这篇关于在 React Native 中动态加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆