Javascript React Native - 使用动态名称的图像需要模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30854232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React Native - Image Require Module using Dynamic Names
提问by Shaheen Ghiassy
I'm currently building a test app using React Native. The Image module, thus far has been working fine.
我目前正在使用 React Native 构建一个测试应用程序。到目前为止,图像模块一直运行良好。
For example, if I had an image named avatar
, the below code snippet works fine.
例如,如果我有一个名为 的图像avatar
,下面的代码片段就可以正常工作。
<Image source={require('image!avatar')} />
But but if I change it to a dynamic string, I get
但是,如果我将其更改为动态字符串,则会得到
<Image source={require('image!' + 'avatar')} />
I get the error:
我收到错误:
Requiring unknown module "image!avatar". If you are sure the module is there, try restarting the packager.
Obviously this is a contrived example, but dynamic image names are important. Does React Native not support dynamic image names?
显然这是一个人为的例子,但动态图像名称很重要。React Native 不支持动态图片名称吗?
采纳答案by Colin Ramsay
This is covered in the documentation under the section "Static Resources":
这包含在“静态资源”部分下的文档中:
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.
引用包中图像的唯一允许方法是在源中逐字写入 require('image!name-of-the-asset')。
// 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} />
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.
但是,您还需要记住在 Xcode 中将图像添加到应用程序中的 xcassets 包中,尽管从您的评论看来您已经这样做了。
回答by BK7
This worked for me :
这对我有用:
I made a custom image component which takes in a boolean to check if the image is from web or is being passed from a local folder.
我制作了一个自定义图像组件,它接受一个布尔值来检查图像是来自网络还是从本地文件夹传递。
// In index.ios.js after importing the component
<CustomImage fromWeb={false} imageName={require('./images/logo.png')}/>
// In CustomImage.js which is my image component
<Image style={styles.image} source={this.props.imageName} />
If you see the code, instead of using one of these:
如果您看到代码,请不要使用以下代码之一:
// NOTE: Neither of these will work
source={require('../images/'+imageName)}
var imageName = require('../images/'+imageName)
I'm just sending the entire require('./images/logo.png')
as a prop. It works!
我只是将整个require('./images/logo.png')
作为道具发送。有用!
回答by Walter Monecke
RELEVANT IF YOU HAVE KNOWN IMAGES (URLS):
如果您知道图像(URL),则相关:
The way I hacked my way through this problem:
我解决这个问题的方式是:
I created a file with an object that stored the image and the name of the image:
我创建了一个文件,其中包含一个存储图像和图像名称的对象:
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 };
Then I imported the object into the component where I want to use it and just do my conditional rendering like so:
然后我将对象导入到我想使用它的组件中,然后像这样进行条件渲染:
import { images } from 'relative/path';
if (cond === 'cat') {
let imgSource = images.cat.uri;
}
<Image source={imgSource} />
I know it is not the most efficient way but it is definitely a workaround.
我知道这不是最有效的方法,但绝对是一种解决方法。
Hope it helps!
希望能帮助到你!
回答by Moso Akinyemi
If you're looking for a way to create a list by looping through a JSON array of your images and descriptions for example, this will work for you.
例如,如果您正在寻找一种通过遍历图像和描述的 JSON 数组来创建列表的方法,这对您有用。
- Create a file (to hold our JSON database) e.g ProfilesDB.js:
- 创建一个文件(保存我们的 JSON 数据库),例如 ProfilesDB.js:
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;
- Then import the data in our component and loop through the list using a FlatList:
- 然后在我们的组件中导入数据并使用 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>
)}
/>
Good luck!
祝你好运!
回答by Abraham Hernandez
As the React Native Documentation says, all your images sources needs to be loaded before compiling your bundle
正如React Native 文档所说,在编译包之前需要加载所有图像源
So another way you can use dynamic images it's using a switch statement. Let's say you want to display a different avatar for a different character, you can do something like this:
因此,您可以使用动态图像的另一种方法是使用 switch 语句。假设您想为不同的角色显示不同的头像,您可以执行以下操作:
class App extends Component {
state = { avatar: "" }
get avatarImage() {
switch (this.state.avatar) {
case "spiderman":
return require('./spiderman.png');
case "batman":
return require('./batman.png');
case "hulk":
return require('./hulk.png');
default:
return require('./no-image.png');
}
}
render() {
return <Image source={this.avatarImage} />
}
}
Check the snack: https://snack.expo.io/@abranhe/dynamic-images
检查小吃:https: //snack.expo.io/@abranhe/dynamic-images
Also, remember if your image it's online you don't have any problems, you can do:
另外,请记住,如果您的图像在线没有任何问题,您可以执行以下操作:
let superhero = "spiderman";
<Image source={{ uri: `https://some-website.online/${superhero}.png` }} />
回答by Ritesh Chitrakar
Important Part here:We cannot concat the image name inside the require like [require('item'+vairable+'.png')]
这里的重要部分:我们不能像 [require('item'+vairable+'.png')] 一样在 require 中连接图像名称
Step 1: We create a ImageCollection.js file with the following collection of image properties
第 1 步:我们使用以下图像属性集合创建一个 ImageCollection.js 文件
ImageCollection.js
================================
export default images={
"1": require("./item1.png"),
"2": require("./item2.png"),
"3": require("./item3.png"),
"4": require("./item4.png"),
"5": require("./item5.png")
}
Step 2: Import image in your app and manipulate as necessary
第 2 步:在您的应用程序中导入图像并根据需要进行操作
class ListRepoApp extends Component {
renderItem = ({item }) => (
<View style={styles.item}>
<Text>Item number :{item}</Text>
<Image source={Images[item]}/>
</View>
);
render () {
const data = ["1","2","3","4","5"]
return (
<FlatList data={data} renderItem={this.renderItem}/>
)
}
}
export default ListRepoApp;
If you want a detailed explanation you could follow the link below Visit https://www.thelearninguy.com/react-native-require-image-using-dynamic-names
如果您需要详细说明,可以点击以下链接访问https://www.thelearninguy.com/react-native-require-image-using-dynamic-names
Courtesy : https://www.thelearninguy.com
回答by Royal.O
import React, { Component } from 'react';
import { Image } from 'react-native';
class Images extends Component {
constructor(props) {
super(props);
this.state = {
images: {
'./assets/RetailerLogo/1.jpg': require('../../../assets/RetailerLogo/1.jpg'),
'./assets/RetailerLogo/2.jpg': require('../../../assets/RetailerLogo/2.jpg'),
'./assets/RetailerLogo/3.jpg': require('../../../assets/RetailerLogo/3.jpg')
}
}
}
render() {
const { images } = this.state
return (
<View>
<Image
resizeMode="contain"
source={ images['assets/RetailerLogo/1.jpg'] }
style={styles.itemImg}
/>
</View>
)}
}
回答by SamYang
you can use
您可以使用
<Image source={{uri: 'imagename'}} style={{width: 40, height: 40}} />
to show image.
显示图像。
from:
从:
https://facebook.github.io/react-native/docs/images.html#images-from-hybrid-app-s-resources
https://facebook.github.io/react-native/docs/images.html#images-from-hybrid-app-s-resources
回答by HannahCarney
First, create a file with image required - React native images must be loaded this way.
首先,创建一个需要图像的文件 - React 原生图像必须以这种方式加载。
assets/index.js
资产/index.js
export const friendsandfoe = require('./friends-and-foe.png');
export const lifeanddeath = require('./life-and-death.png');
export const homeandgarden = require('./home-and-garden.png');
Now import all your assets
现在导入您的所有资产
App.js
应用程序.js
import * as All from '../../assets';
You can now use your image as an interpolated value where imageValue (coming in from backend) is the same as named local file ie: 'homeandgarden':
您现在可以将您的图像用作内插值,其中 imageValue(来自后端)与命名的本地文件相同,即:'homeandgarden':
<Image style={styles.image} source={All[`${imageValue}`]}></Image>
回答by Vasanth
Say if you have an application which has similar functionality as that of mine. Where your app is mostly offline and you want to render the Images one after the other. Then below is the approach that worked for me in React Native version 0.60.
假设您有一个与我的应用程序具有类似功能的应用程序。您的应用程序大部分处于离线状态,并且您想要一个接一个地呈现图像。然后下面是在 React Native 0.60 版中对我有用的方法。
- First create a folder named Resources/Imagesand place all your images there.
- Now create a file named Index.js(at Resources/Images) which is responsible for Indexing all the images in the Reources/Imagesfolder.
- 首先创建一个名为Resources/Images的文件夹并将所有图像放在那里。
- 现在创建一个名为Index.js(在 Resources/Images)的文件,它负责索引Reources/Images文件夹中的所有图像。
const Images = { 'image1': require('./1.png'), 'image2': require('./2.png'), 'image3': require('./3.png') }
const Images = { 'image1': require('./1.png'), 'image2': require('./2.png'), 'image3': require('./3.png') }
- Now create a Component named ImageView at your choice of folder. One can create functional, class or constant component. I have used Const component. This file is responsible for returning the Image depending on the Index.
- 现在在您选择的文件夹中创建一个名为 ImageView 的组件。可以创建函数、类或常量组件。我使用了 Const 组件。该文件负责根据索引返回图像。
import React from 'react'; import { Image, Dimensions } from 'react-native'; import Images from './Index'; const ImageView = ({ index }) => { return ( <Image source={Images['image' + index]} /> ) } export default ImageView;
import React from 'react'; import { Image, Dimensions } from 'react-native'; import Images from './Index'; const ImageView = ({ index }) => { return ( <Image source={Images['image' + index]} /> ) } export default ImageView;
Now from the component wherever you want to render the Static Images dynamically, just use the ImageView component and pass the index.
< ImageView index={this.qno + 1} />
现在,从您想要动态渲染静态图像的组件开始,只需使用 ImageView 组件并传递索引。
< ImageView index={this.qno + 1} />