- React Native Cookbook
- Dan Ward
- 432字
- 2025-04-04 14:57:29
How it works...
In step 2, we required the Image component. This is the component responsible for rendering images from the local filesystem on the device or from a remote server.
In step 3, we required all of the images. It's good practice to require the images outside of the component in order to only require them once. On every renderer, React Native will use the same image. If we were dealing with dynamic images from a remote server, then we'd need to require them on every renderer.
The require function accepts the path of the image as a parameter. The path is relative to the folder that our class is in. For remote images, we need to use an object defining uri for where our file is.
In step 4, a stateless component was declared. We used remoteImage as the background of our application via an ImageBackground element, since Image elements cannot have child elements. This element acts similarly to the background-url property in CSS.
The source property of Image accepts an object to load remote images or a reference to the required file. It's very important to explicitly require every image that we want to use because when we prepare our application for distribution, images will be added to the bundle automatically. This is the reason we should avoid doing anything dynamic, such as the following:
const iconName = playing ? 'pause' : 'play'; const icon = require(iconName);
The preceding code won't include the images in the final bundle. As a result, we'll have errors when trying to access these images. Instead, we should refactor our code to something like this:
const pause = require('pause'); const play = require('playing'); const icon = playing ? pause : play;
This way, the bundle will include both images when preparing our application for distribution, and we can decide which image to display dynamically at runtime.
In step 5, we defined the styles. Most of the properties are self-explanatory. Even though the images we're using for icons are white, I've added the tintColor property to show how it can be used to color images. Give it a try! Change tintColor to #f00 and watch the icons turn red.
Flexbox is being used to align different portions of the layout. Flexbox in React Native behaves essentially the same as it does in web development. We'll discuss flexbox more in the Using flexbox to create a layout recipe later in this chapter, but the complexities of flexbox itself are outside the scope of this book.