React Native - Image Require Module using Dynamic Names

前端 未结 14 1145
夕颜
夕颜 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 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 
      }
    }
    

    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";
    
    
    

提交回复
热议问题