我需要将某些图像的地址置于对象中,以使这些图像能够在FlatList中呈现。但是我面临一个错误。有人知道这是否可能吗?
import React, {Component} from 'react';
import {View, Text, FlatList, Image, StyleSheet} from 'react-native';
export default class App extends Component{
constructor(){
super();
this.state = {
dados:[
{nome:'Feijoada', preco: 29.99, img:'./img/batata.jpg'},
{nome:'Batata Frita', preco: 14.99, img:'./img/feijoada.jpg'},
{nome:'Strogonoff de frango', preco: 16.99, img:'./img/macarrao.jpg' },
{nome:'Macarrão na chapa', preco: 9.99, img:'./img/batata.jpg'}
]
};
}
render(){
return(
<View>
<FlatList data={this.state.dados} renderItem={({item})=>
<View>
<Text>{item.nome}</Text>
<Text>{item.preco}</Text>
<Image source={require(item.img)}/>
</View>
}/>
</View>
);
}
}
答案 0 :(得分:1)
您有两个选择
尝试一下
1。
import React, {Component} from 'react';
import {View, Text, FlatList, Image, StyleSheet} from 'react-native';
export default class App extends Component{
constructor(){
super();
this.state = {
dados:[
{nome:'Feijoada', preco: 29.99, img:'./img/batata.jpg'},
{nome:'Batata Frita', preco: 14.99, img:'./img/feijoada.jpg'},
{nome:'Strogonoff de frango', preco: 16.99, img:'./img/macarrao.jpg' },
{nome:'Macarrão na chapa', preco: 9.99, img:'./img/batata.jpg'}
]
};
}
render(){
return(
<View>
<FlatList data={this.state.dados} renderItem={({item})=>
<View>
<Text>{item.nome}</Text>
<Text>{item.preco}</Text>
<Image source={{ uri: item.img }}/>
</View>
}/>
</View>
);
}
}
2。
import React, {Component} from 'react';
import {View, Text, FlatList, Image, StyleSheet} from 'react-native';
export default class App extends Component{
constructor(){
super();
this.state = {
dados:[
{nome:'Feijoada', preco: 29.99, img:require('./img/batata.jpg'},
{nome:'Batata Frita', preco: 14.99, img:require('./img/feijoada.jpg')},
{nome:'Strogonoff de frango', preco: 16.99, img:require('./img/macarrao.jpg') },
{nome:'Macarrão na chapa', preco: 9.99, img:require('./img/batata.jpg')}
]
};
}
render(){
return(
<View>
<FlatList data={this.state.dados} renderItem={({item})=>
<View>
<Text>{item.nome}</Text>
<Text>{item.preco}</Text>
<Image source={item.img}/>
</View>
}/>
</View>
);
}
}