我目前正在使用 React Native 构建一个测试应用程序。 图像模块,到目前为止都挺好
例如,如果我有一个名为avatar的图片,下面的代码片段可以很好地完成任务。
<Image source={require('image!avatar')} />
但是如果我把它变成一个动态字符串,就成了
<Image source={require('image!' + 'avatar')} />
出现一个error:
Requiring unknown module "image!avatar". If you are sure the module is there, try restarting the packager.
React Native 不支持动态映像名称吗?
我是这样做的:
制作一个自定义图像组件,接受 boolean来检查图像是来自网络还是来自本地文件夹。
// In index.ios.js after importing the component
// In CustomImage.js which is my image component
别用下面的代码:
// NOTE: Neither of these will work
source={require('../images/'+imageName)} var imageName = require('../images/'+imageName)
这个 require('./images/logo.png')就能行了!
如果你有已知的图片(url) :
那我会这么操作:
我创建了一个文件,其中包含一个存储图像和图像名称的对象:
const images = {
dog: {
imgName: 'Dog',
uri: require('path/to/local/image')
},
cat: {
imgName: 'Cat on a Boat',
uri: require('path/to/local/image')
}}
export { images };
然后我把这个对象导入到我想要使用它的组件中,然后像这样做条件渲染:
import { images } from 'relative/path';
if (cond === 'cat') {
let imgSource = images.cat.uri;}
<Image source={imgSource} />
我知道这不一定是最管用的方法,但这绝对是一种变通方法。
希望能有所帮助!
如果您正在想办法,通过循环遍历图像和描述的 JSON 数组来创建列表,那么下文对你有用。
先创建file:
const Profiles=[
{
"id" : "1",
"name" : "Peter Parker",
"src" : require('../images/user1.png'),
"age":"70",
},
{
"id" : "2",
"name" : "Barack Obama",
"src" : require('../images/user2.png'),
"age":"19",
},
{
"id" : "3",
"name" : "Hilary Clinton",
"src" : require('../images/user3.png'),
"age":"50",
}]export default Profiles;
然后导入组件中的数据,使用 FlatList 循环遍历列表:
import Profiles from './ProfilesDB.js';
<FlatList
data={Profiles}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => <View>
<Image source={item.src} />
<Text>{item.name}</Text>
</View>
}/>
祝你好运!
”Static Resources”一节下的文件介绍了这一点:
唯一允许在 bundle 中引用映像的方法是在源代码中直接写入 require (‘ image! name-of-The-asset')。
// GOOD<Image source={require('image!my-icon')} />
// BADvar icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';<Image source={require('image!' + icon)} />
// GOODvar icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');<Image source={icon} />
然而,你也需要记住将你的图片添加到你在 Xcode 的应用程序的 xcasset 包中,尽管,你似乎已经这样做了。
http://facebook.github.io/react-native/docs/image.html#adding-static-resources-to-your-app-using-images-xcassets