React Native中需要非静态映像



我的React Native应用程序中有一个特殊的文件夹,里面有图像。这些图片的路径存储在作为道具传递给卡片组件的特殊对象中。所以,我不能使用require,因为它只使用静态路径字符串。如何使用从道具加载这些图像?这是我的尝试:

import React from 'react';
import {
View,
Text,
Image,
TouchableOpacity,
StyleSheet
} from 'react-native';
import EmptyImage from '../data/images/empty-image.jpg';
class Card extends React.Component {
constructor(props) {
super(props);
}
render() {
const { myObject } = this.props;
return (
<View>
<Image 
source={
myObject.imagesNames[0] ?
require(`../data/images/${myObject.imagesNames[0]}`)
:
EmptyImage
}  
/> 
</View>
);
}
}
export default Card;

由于您的图像是本地的,因此最好通过要求下面的图像来创建json对象

images={
image1:require('path'),
image2:require('path2'),
};

你可以设置如下的网址

<Image source={
myObject.imagesNames[0] ?images[imagesNames[0]]:EmptyImage
}  
/> 

最新更新