如何在对象上放置图像地址? FlatList

时间:2019-09-11 13:43:11

标签: react-native

我需要将某些图像的地址置于对象中,以使这些图像能够在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>
    );
  }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

您有两个选择

  • 如果图像存储在远程URL中,则将对象与uri一起使用
  • 在状态中使用require获取所有图像

尝试一下

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>
        );
      }
    }