简体   繁体   English

动态需要React Native图像

[英]Dynamic requiring React Native images

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 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. 所以考虑到我在这里找到的SO响应,我想创建一个带有switch语句的函数,该函数在传递正确的标志代码时会返回所需的图像。 Something like the below. 像下面这样的东西。

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

I'll have well over 200 cases given this solution. 给出这个解决方案,我将有超过200个案例。 Is there some better way to do this? 有没有更好的方法来做到这一点?

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 ? 由于手动要求所有图像的繁琐程度,您可以将它们添加到App图像资源并通过uri要求它们吗?

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

Other than that I think your proposal is the only other solution.. you could clean it up slightly by making it a JS module. 除此之外,我认为您的提案是唯一的其他解决方案..您可以通过将其作为JS模块进行轻微清理。

Flags.js 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')
...

Then just reference it like so. 然后就这样引用它。

Component.js Component.js

import Flags from './Flags'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM