React-Native Image Invalid prop 'source' supplied to Image

前端 未结 2 846
春和景丽
春和景丽 2021-01-12 13:18

I think this is a very annoying bug and feels like there is no solution but I want to share and ask.. I fetch data from server and I get image source from there and I use sa

2条回答
  •  臣服心动
    2021-01-12 14:00

    This is not the recommended way to assign dynamically images since React Native must know all your images sources before compiling your bundle.

    According to the docs, here's an example of how to load images dynamically:

    // GOOD
    ;
    
    // BAD
    var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
    ;
    
    // GOOD
    var icon = this.props.active
      ? require('./my-icon-active.png')
      : require('./my-icon-inactive.png');
    ;
    

    https://facebook.github.io/react-native/docs/images.html

    Hope it helps

    Edit: If you know all the images that could be loaded, you can try something like this:

    // Create a file containing the references for your images
    
    // images.js
    const images = {
      logo: {
        uri: require('your-image-path/logo.png')
      },
      banner: { 
        uri: require('your-image-path/banner.png')
      }
    }
    
    export { images }; 
    
    
    //YourComponent.js
    import { images } from 'yourImagesPath';
    
    // for this test, expected to return [ { name: logo }, { name: banner} ]
    const imagesFromTheServer = (your fetch);
    
    imagesFromTheServer.map(image => {
      if (!images[image]) {
        return Image not found;
      }
      return ; // if image = logo, it will return images[logo] containing the require path as `uri` key
    });
    

    This is quite hacky but may work.

    Let me know if it helped

提交回复
热议问题