React Native Dynamic Images

后端 未结 1 1619
悲&欢浪女
悲&欢浪女 2020-12-17 06:36

I\'m reading a JSON file which has the names and the image URI of certain people. While iterating over the structure I\'m able to print the names but can\'t get the Images t

1条回答
  •  旧巷少年郎
    2020-12-17 07:10

    Depending on the number of images that you are expecting you could try placing an images.js file in your assets/images folder and require them as such:

    // assets/images/images.js
    const images = {
     rohit: require("./rohit.png"),
     bhavya: require("./bhayva.png")
    }
    export default images;
    

    Then in your MainComponent, if you were to trim off the assets:/ part of the string in the uri then you could use:

    import images from "../assets/images"
    
    {initialArr.map((prop, key) => {
      return (
        
          
          {prop.uri}
        
      );
    })}
    

    If you are dealing with a large number of images, then your images.js file will become difficult to maintain, in that case you could try using a plugin like https://github.com/dushaobindoudou/babel-plugin-require-all and then write a small script which will create an dictionary of your images like:

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

    0 讨论(0)
提交回复
热议问题