我有一个名为“ Bread.json”的json文件,以下是该文件的内容。
如何在<Image>
中动态使用图片名称
我正在尝试追踪,但出现错误。我正在将图像名称的数组从json文件放入Flatlist
,所以{item.img} = my image name from json file
。但是不起作用!
<Image source={require('../images/'+{item.img})} />
因此,如何在<Image>
的源代码中使用图像名称,也不能在我的json文件中使用require()
函数。有帮助吗?
“ bread.json”
[
{
"id": "1",
"img": "1.jpg",
"cat": "Breakfast",
"title": "Small Semolina Griddle Breads"
},
{
"id": "2",
"img": "2.jpg",
"cat": "Side",
"title": "Corn Bread"
},
{
"id": "3",
"img": "3.jpg",
"cat": "Appetizer",
"title": "Fresh Tomato Bruschetta"
}
]
答案 0 :(得分:1)
您可以尝试!
<Image source={getImageSource(item.img)} />
function getImageSource(image) {
let imageSrc = require('../images/logo.png');
switch (image) {
case "1.jpg":
imageSrc = require('../images/1.jpg');
break;
default:
break;
}
return imageSrc;
}
答案 1 :(得分:1)
希望这会有所帮助!
1)创建一个文件(用于保存JSON数据),例如,bread.js:
<ul>
<ng-container *ngFor="let status of statuses$ | async">
<li *ngIf="status.name != post.statusName">
{{status.name}}
</li>
</ng-container>
</ul>
2)然后将数据导入组件中,并使用FlatList在列表中循环
const Breads=[
{
"id": "1",
"img" : require('../images/1.jpg'),
"cat": "Breakfast",
"title": "Small Semolina Griddle Breads"
},
{
"id": "2",
"img" : require('../images/2.jpg'),
"cat": "Side",
"title": "Corn Bread"
},
{
"id": "3",
"img" : require('../images/3.jpg'),
"cat": "Appetizer",
"title": "Fresh Tomato Bruschetta"
}
]
export default Breads;