[英]Adding dynamic local images in a react native listview
I'm trying to load some local images in a simple app that I'm making using react native. 我试图在我使用react native制作的简单应用程序中加载一些本地图像。
I'm following the guide here - https://facebook.github.io/react-native/docs/images.html 我在这里遵循指南-https: //facebook.github.io/react-native/docs/images.html
Unfortunately, that guide says the following: 不幸的是,该指南指出:
Note that in order for this to work, the image name in require has to be known statically.
请注意,为了使此功能起作用,必须静态知道require中的图像名称。
Which is why my code isn't working when I try to render rows in a list view: 这就是为什么当我尝试在列表视图中呈现行时代码不起作用的原因:
renderRow(chat){
return (
<View style={ styles.row }>
<Image
source={require(`../images/${chat.image}`)} //this is the part that's not working. It can't require a dynamic path
style={ styles.cellImage }
/>
</View>
);
}
How can I achieve this? 我该如何实现? Or can you suggest another way that will work?
还是可以建议另一种可行的方法?
It's quirky and odd, but if you have a set number of options for the images (which makes sense if the images are living in the project) then you can return the statically required image based on a given condition. 这是古怪而奇怪的,但是如果您有一定数量的图像选项(如果图像位于项目中,这是有意义的),则可以根据给定条件返回静态所需的图像。
getSource() {
if (condition) {
return require( '../images/option-one' );
} else {
return require( '../images/default-option' );
}
}
renderRow(chat){
return (
<View style={ styles.row }>
<Image
source={ this.getSource() }
style={ styles.cellImage }
/>
</View>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.