Rendering local images from database

那年仲夏 提交于 2021-01-29 06:37:35

问题


I'm making a country picker with flags. The country names and flag image name is coming from database, like this (sample):

dataSource: [
{
  id: 1,
  name: "Afghanistan",
  image: '../assets/flags/af.png'
},
{
  id: 2,
  name: "Bahrain",
  image: '../assets/flags/ba.png'
},
{
  id: 3,
  name: "Canada",
  image: '../assets/flags/ca.png'
}]

Then I send that dataSource to my component

                        <CountryPickerFlags
                          dataSource={this.state.dataSource}
                        />

Then in the component FlatList (renderItem) I do:

  _renderItemListValues(item, index) {
      var image_uri = {uri: item.image} ;   
      
      console.log(JSON.stringify(image_uri));
        
    return (
    
      <TouchableOpacity
        activeOpacity={1}
        style={styles.listRowClickTouchStyle}
        onPress={() => this._setSelectedIndex(item.id, item.name)}
      >
        <View style={[styles.listRowContainerStyle,{ flexDirection:'row', justifyContent: 'center', alignItems: 'center'}]} >
          <Image source={image_uri} />
          <Text style={styles.listTextViewStyle}>{item.name}</Text>
        </View>
      </TouchableOpacity>
    );
  }

But the flag is not rendered.... If I hardcode the image (with require) it's working...

  <Image source={require("../assets/flags/af.png")} />

How can I do it?


回答1:


Go to assets folder and create a file prepareImages.js and paste inside the following:

const fs = require("fs");
const files = fs.readdirSync("./assets/flags").filter(x => x.includes("png"));
const ex = "{\n" +
files.map(x => `"../assets/flags/${x}": require("./${x}"),`).join("\n") + "}";
const res = "export default " + ex;
fs.writeFileSync("./assets/flags/index.js", res);

This will create an index.js file where will be an object like that:

"../assets/flags/af.png": require("./af.png"),

Import images from this file where you render Image component.

import images from "../assets/flags/images";

Render image source like that:

<Image source={images[image_uri]} />



回答2:


Add require to your data set like

dataSource: [ { ..., image: require('../assets/flags/af.png')}]


来源:https://stackoverflow.com/questions/65354887/rendering-local-images-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!