Static picture Resources
When the React Native0.14 version was released, it provided a unified way to manage images for iOS and Android apps. Add a static picture to your app and then refer to it in your source tree, such as:
1 <image source={require ('./my-icon.png ')}/>
The resolution of the image name problem is consistent with the solution of JS module. In the example above, Packager will request the same directory of its components to look for my-icon.png。如果你同时有
my-icon.ios.png和
my-icon.android.png
, and Packager will decide which image to retrieve depending on the platform you are running.
You can also use @2x
@3x等。
them to provide images for different screen resolutions. For example, you have the following file structure:
1 . 2 ├──button.js 3 └──img 4 ├──[email protected]5 └──[email protected]
button.js
The code contains the following:
1 <image source={require ('./img/check.png ')}/>
Packager will automatically match the screen resolution, for example, the iphone 5s will be selected [email protected]
, the Nexus 5 will be chosen[email protected]。如果没有图片匹配这屏幕分辨率,就会选择最接近最好的。
Some benefits:
- IOS and Android Use the same program system.
- The picture and your JS code are in the same directory, and the components are self-contained.
- Without a global namespace, you don't have to worry about name collisions.
- Only images that are really used will be packaged into your app.
- Adding or changing a picture does not require the app to recompile, just use it for normal operation in the emulator.
- Packager knows the size of the picture and does not need to write the duplicate code.
- Images can be distributed via NPM packages.
Note: In order to work properly, the picture name in require must be static
1 //Good2<image Source={require ('./my-icon.png ')}/>3 4 // Bad5 varicon = This. props.active? ' my-icon-active ': ' My-icon-inactive ';6<image source={require ('./' + icon + '. png ')}/>7 8 //Good9 varicon = This. props.active? Require ('./my-icon-active.png '): Require ('./my-icon-inactive.png '));Ten<image Source={icon}/>
React Native Image