React Native - 使用动态名称的图像需求模块 [英] React Native - Image Require Module using Dynamic Names
问题描述
我目前正在使用React Native构建测试应用。到目前为止,Image模块工作正常。
I'm currently building a test app using React Native. The Image module, thus far has been working fine.
例如,如果我有一个名为 avatar
的图像,以下代码段工作正常。
For example, if I had an image named avatar
, the below code snippet works fine.
<Image source={require('image!avatar')} />
但是如果我将其更改为动态字符串,我会得到
But but if I change it to a dynamic string, I get
<Image source={require('image!' + 'avatar')} />
我收到错误:
Requiring unknown module "image!avatar". If you are sure the module is there, try restarting the packager.
显然这是一个人为的例子,但动态图像名称很重要。 React Native不支持动态图像名称吗?
Obviously this is a contrived example, but dynamic image names are important. Does React Native not support dynamic image names?
推荐答案
这在静态资源:
唯一允许引用捆绑中图像的方法是在源中逐字写入require('image!of the-asset')。
The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.
// GOOD
<Image source={require('image!my-icon')} />
// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('image!' + icon)} />
// GOOD
var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');
<Image source={icon} />
然而,您还需要记住将图像添加到Xcode中的应用程序中的xcassets包中,你的评论似乎已经完成了。
However you also need to remember to add your images to an xcassets bundle in your app in Xcode, though it seems from your comment you've done that already.
http://facebook.github.io/react-native/docs/image.html#adding-static-资源到你的app-using-images-xcassets
这篇关于React Native - 使用动态名称的图像需求模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!