动态需要React Native图像 [英] Dynamic requiring React Native images

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

问题描述

我正在努力在我的反应原生项目中包含一些标志来代表国家/地区。我发现你不能动态地要求像下面的例子中的图像作为反应原生。

I'm working on including some flags to represent countries in my react native project. I discovered that you can't dynamically require images like the example below in react native.

require(`../assets/flags/32/${countryCode}.png`)

所以考虑到SO响应,我发现这里我正在考虑创建一个带有switch语句的函数传递正确的标志代码时,返回所需的图像。如下所示。

So given the SO response I found here I was thinking of creating a function with a switch statement that would return the required image back when passed the correct flag code. Something like the below.

export const Flags = (countryCode) => {
 switch (countryCode) {
   case 'US':
    return require('../assets/flags/32/US.png');
   ....
 }
};

考虑到这个解决方案,我将有200多个案例。有没有更好的方法呢?

I'll have well over 200 cases given this solution. Is there some better way to do this?

推荐答案

由于手动要求所有图像的繁琐程度,你能不能将它们添加到您的App图像资源中并通过 uri 要求他们?

Because of how cumbersome it would be to manually require all the images, can you add them to your App image assets and require them via uri?

<Image source={{uri: 'flags/32/'+countryCode}} style={{width: 32, height: 32}} />

除此之外,我认为您的提案是唯一的其他解决方案..您可以稍微清理一下使它成为JS模块。

Other than that I think your proposal is the only other solution.. you could clean it up slightly by making it a JS module.

Flags.js

exports.US = require('../assets/flags/32/US.png')
exports.UK = require('../assets/flags/32/UK.png')
exports.FR = require('../assets/flags/32/FR.png')
exports.JP = require('../assets/flags/32/JP.png')
...

然后就这样引用它。

Component.js

import Flags from './Flags'

<Image source={Flags[countryCode]} style={{width: 32, height: 32}} />

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

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