Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've component in my application which works fine if it is assigned direct string value("someImage.png"), but if I try to assign it by storing image name in a local variable it gives this exception "require() must have a single string literal argument" This line works fine

<ImageBackground source={require("./Resources/bg/imageone.png")} resizeMode='cover' style={customStyles.backdrop}>

Issue occurs in this case

let imageName = "./Resources/bg/imageone.png";          
<ImageBackground id="123" source={require(imageName)} resizeMode='cover' style={customStyles.backdrop}>

I also found same issue reported here, but no one has answered that yet. Can you help me out here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
270 views
Welcome To Ask or Share your Answers For Others

1 Answer

This example of dynamic images can also show how to correctly assign a variable with the image source value. The recommendation is to assign the whole require in a variable, instead of just its value.

// GOOD
<Image source={require('./my-icon.png')} />;

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

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

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

Hope it helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...