Home >Web Front-end >JS Tutorial >How Can I Dynamically Load Images in React Native\'s Image Require Module?
Dynamic Image Names in React Native Image Require Module
In React Native, the Image Require module allows developers to load static image resources into their applications. While the module works flawlessly with static image filenames, dynamic image names often lead to errors.
Issue:
A developer attempts to use a dynamic string for the image filename:
<Image source={require('image!' + 'avatar')} />
However, React Native throws an error indicating an unknown module, as depicted below:
Requiring unknown module "image!avatar". If you are sure the module is there, try restarting the packager.
Resolution:
According to the React Native documentation's "Static Resources" section, image names must be statically specified in the source attribute:
// GOOD <Image source={require('image!my-icon')} />
Using dynamic strings for image filenames is explicitly discouraged:
// BAD var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive'; <Image source={require('image!' + icon)} />
Instead, the solution is to utilize conditional rendering to assign static image filenames to a variable:
// GOOD var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive'); <Image source={icon} />
Additional Considerations:
The above is the detailed content of How Can I Dynamically Load Images in React Native\'s Image Require Module?. For more information, please follow other related articles on the PHP Chinese website!