React Native - Image Require Module using Dynamic Names

前端 未结 14 890
夕颜
夕颜 2020-11-22 11:29

I\'m currently building a test app using React Native. The Image module, thus far has been working fine.

For example, if I had an image named avatar, th

相关标签:
14条回答
  • 2020-11-22 11:50
    import React, { Component } from 'react';
    import { Image } from 'react-native';
    
    class Images extends Component {
      constructor(props) {
        super(props);
        this.state = {
               images: {
                    './assets/RetailerLogo/1.jpg': require('../../../assets/RetailerLogo/1.jpg'),
                    './assets/RetailerLogo/2.jpg': require('../../../assets/RetailerLogo/2.jpg'),
                    './assets/RetailerLogo/3.jpg': require('../../../assets/RetailerLogo/3.jpg')
                }
        }
      }
    
      render() {
        const {  images } = this.state 
        return (
          <View>
            <Image
                                resizeMode="contain"
                                source={ images['assets/RetailerLogo/1.jpg'] }
                                style={styles.itemImg}
                            />
         </View>
      )}
    }
    
    0 讨论(0)
  • 2020-11-22 11:54

    RELEVANT IF YOU HAVE KNOWN IMAGES (URLS):

    The way I hacked my way through this problem:

    I created a file with an object that stored the image and the name of the image:

    const images = {
      dog: {
        imgName: 'Dog', 
        uri: require('path/to/local/image')
      },
      cat: {
        imgName: 'Cat on a Boat', 
        uri: require('path/to/local/image')
      }
    }
    
    export { images };
    

    Then I imported the object into the component where I want to use it and just do my conditional rendering like so:

    import { images } from 'relative/path';
    
    if (cond === 'cat') {
      let imgSource = images.cat.uri;
    }
    
    <Image source={imgSource} />
    

    I know it is not the most efficient way but it is definitely a workaround.

    Hope it helps!

    0 讨论(0)
  • 2020-11-22 11:56

    First, create a file with image required - React native images must be loaded this way.

    assets/index.js

    export const friendsandfoe = require('./friends-and-foe.png'); 
    export const lifeanddeath = require('./life-and-death.png'); 
    export const homeandgarden = require('./home-and-garden.png');
    

    Now import all your assets

    App.js

    import * as All  from '../../assets';
    

    You can now use your image as an interpolated value where imageValue (coming in from backend) is the same as named local file ie: 'homeandgarden':

    <Image style={styles.image} source={All[`${imageValue}`]}></Image>
    
    0 讨论(0)
  • 2020-11-22 11:57

    This is covered in the documentation under the section "Static Resources":

    The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.

    // GOOD
    <Image source={require('image!my-icon')} />
    
    // BAD
    var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
    <Image source={require('image!' + icon)} />
    
    // GOOD
    var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');
    <Image source={icon} />
    

    However you also need to remember to add your images to an xcassets bundle in your app in Xcode, though it seems from your comment you've done that already.

    http://facebook.github.io/react-native/docs/image.html#adding-static-resources-to-your-app-using-images-xcassets

    0 讨论(0)
  • 2020-11-22 11:58

    This worked for me :

    I made a custom image component which takes in a boolean to check if the image is from web or is being passed from a local folder.

    // In index.ios.js after importing the component
    <CustomImage fromWeb={false} imageName={require('./images/logo.png')}/>
    
    // In CustomImage.js which is my image component
    <Image style={styles.image} source={this.props.imageName} />
    

    If you see the code, instead of using one of these:

    // NOTE: Neither of these will work
    source={require('../images/'+imageName)} 
    var imageName = require('../images/'+imageName)
    

    I'm just sending the entire require('./images/logo.png') as a prop. It works!

    0 讨论(0)
  • 2020-11-22 12:00

    As the React Native Documentation says, all your images sources needs to be loaded before compiling your bundle

    So another way you can use dynamic images it's using a switch statement. Let's say you want to display a different avatar for a different character, you can do something like this:

    class App extends Component {
      state = { avatar: "" }
    
      get avatarImage() {
        switch (this.state.avatar) {
          case "spiderman":
            return require('./spiderman.png');
          case "batman":
            return require('./batman.png');
          case "hulk":
            return require('./hulk.png');
          default:
            return require('./no-image.png');
        }
      }
    
      render() {
        return <Image source={this.avatarImage} />
      }
    }
    

    Check the snack: https://snack.expo.io/@abranhe/dynamic-images

    Also, remember if your image it's online you don't have any problems, you can do:

    let superhero = "spiderman";
    
    <Image source={{ uri: `https://some-website.online/${superhero}.png` }} />
    
    0 讨论(0)
提交回复
热议问题