React Native Getting Started Project and Analysis

React Native Getting Started Project and Analysis

You can successfully create a new project by setting up the React Native environment and creating a project (Mac), that is, directly create it using the following statement:

  1. //Command line to create a project:
  2.  
  3. react-native init AwesomeProject

After the creation is successful, we, the beginners, mainly focus on two files:

1) AppDelegate.m in the iOS project directory

It is the entry point for connecting the iOS project to the js file and related initialization operations.

2) index.ios.js in the root directory

This is the js entry file corresponding to iOS.

1. Parsing AppDelegate.m in iOS project

1. The AppDelegate.m code is as follows:

  1. #import "AppDelegate.h"  
  2.  
  3. // React Native related header files
  4.  
  5. #import "RCTBundleURLProvider.h"  
  6.  
  7. #import "RCTRootView.h"  
  8.  
  9. @implementation AppDelegate
  10.  
  11. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  12.  
  13. {
  14.  
  15. NSURL *jsCodeLocation;
  16.  
  17. /*
  18.  
  19. When the app starts running, RCTRootView will load the app from the following URL: (When debugging locally, it is loaded directly from index.ios in the local server . The settings are different when publishing)
  20.  
  21. This re-invokes the terminal window you opened when running the app, which starts a packager and server to handle the above request.
  22.  
  23. Open that URL in Safari; you’ll see the app’s JavaScript code.
  24.  
  25. */
  26.  
  27. [[RCTBundleURLProvider sharedSettings] setDefaults];
  28.  
  29. jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@ "index.ios" fallbackResource:nil];
  30.  
  31. // RCTRootView is a UIView container that hosts the React Native application. It also provides an interface to connect the native end and the managed end.
  32.  
  33. RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
  34.  
  35. moduleName:@ "AwesomeProject"  
  36.  
  37. initialProperties:nil
  38.  
  39. launchOptions:launchOptions];
  40.  
  41. rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  42.  
  43. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  44.  
  45. UIViewController *rootViewController = [UIViewController new];
  46.  
  47. rootViewController.view = rootView ;
  48.  
  49. self.window.rootViewController = rootViewController;
  50.  
  51. [self.window makeKeyAndVisible];
  52.  
  53. return YES;
  54.  
  55. }
  56.  
  57. @ end  

2. RCTRootView

RCTRootView encapsulates the React Natvie view into a native component. (Everything the user can see comes from this RootView, and all initialization work is done in this method.)

Analysis:

You can pass arbitrary properties to the React Native app through the RCTRootView initializer.

The initialProperties parameter must be an instance of NSDictionary.

This dictionary parameter will be converted internally into a JSON object that can be called by the JS component.

  1. NSArray *imageList = @[@ "http://foo.com/bar1.png" ,
  2.  
  3. @ "http://foo.com/bar2.png" ];
  4.  
  5. NSDictionary *propsDict = @{@ "images" : imageList};
  6.  
  7. RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
  8.  
  9. moduleName:@ "AwesomeProject"  
  10.  
  11. initialProperties: propsDict
  12.  
  13. launchOptions:launchOptions];

In the js file, the parameters defined above are called through this.props.images.

this is the component registered by AppRegistry.registerComponent (described below)

RCTRootView also provides a read-write property appProperties. After appProperties is set, the React Native app will re-render according to the new properties. Of course, the update will only be triggered if the new properties are different from the previous properties.

(Note: 1. You can update properties at any time, but the update must be done in the main thread, and the read can be done in any thread. 2. When updating properties, it is not possible to update only part of the properties)

  1. NSArray *imageList = @[@ "http://foo.com/bar3.png" ,
  2.  
  3. @ "http://foo.com/bar4.png" ];
  4.  
  5. rootView.appProperties = @{@ "images" : imageList};

2. Parse the js entry file (index.ios.js)

1. The index.ios.js code is as follows:

  1. 'use strict' ; // Globally enter strict mode (currently found that it is not necessary)
  2.  
  3. /**<
  4.  
  5. Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors;
  6.  
  7. Eliminate some insecurity in code operation and ensure the safety of code operation;
  8.  
  9. Improve compiler efficiency and increase running speed;
  10.  
  11. Pave the way for future new versions of Javascript.
  12.  
  13. */
  14.  
  15. //Import some necessary modules
  16.  
  17. // React Native built-in components can be directly imported via { xxx } from   'react-native' to import, of course, you can also customize the components.
  18.  
  19. import React, { Component } from   'react' ;
  20.  
  21. import {
  22.  
  23. AppRegistry,
  24.  
  25. StyleSheet,
  26.  
  27. Text,
  28.  
  29. View ,
  30.  
  31. TouchableOpacity
  32.  
  33. } from   'react-native' ;
  34.  
  35. //Class, this is the default loading class, inherited from Component, Component class (component) is similar to View in Android and iOS  
  36.  
  37. //Here is a component
  38.  
  39. class AwesomeProject extends Component {
  40.  
  41. //Constructor, each component has its own properties (props) and state (state)
  42.  
  43. //When calling this.setState to change the state text or isTouchDown, the component will trigger the render function to render and update
  44.  
  45. constructor(props) {
  46.  
  47. super(props);
  48.  
  49. this.state = {
  50.  
  51. text: 'Welcome to React Native!' ,
  52.  
  53. isTouchDown: false  
  54.  
  55. };
  56.  
  57. }
  58.  
  59. //Called once before the initial rendering, where preprocessing operations can be performed
  60.  
  61. //In React, setting this.state will cause re-rendering, but setting this.state in componentWillMount will not cause render to be called multiple times
  62.  
  63. //The component life cycle will be further explained later
  64.  
  65. componentWillMount() {
  66.  
  67. }
  68.  
  69. //Rendering function, used to render the actual visible part of the Component
  70.  
  71. render() {
  72.  
  73. //var defines variables and changes the corresponding values ​​according to the status values
  74.  
  75. var welcomeText = this.state.text;
  76.  
  77. var bgcolor;
  78.  
  79. if (this.state.isTouchDown) {
  80.  
  81. bgcolor = '#c5c5ab' ;
  82.  
  83. } else {
  84.  
  85. bgcolor = '#F5FCFF' ;
  86.  
  87. }
  88.  
  89. console.log( 'testtststststts' );
  90.  
  91. //The returned content is displayed on the interface
  92.  
  93. return (
  94.  
  95. < View style={[styles.container, {backgroundColor: bgcolor}]}>
  96.  
  97. <Text style={styles.welcome}>
  98.  
  99. {welcomeText}
  100.  
  101. </Text>
  102.  
  103. <Text style={styles.instructions}>
  104.  
  105. To get started, edit index .android.js
  106.  
  107. </Text>
  108.  
  109. <Text style={styles.instructions}>
  110.  
  111. Shake or press menu button for dev menu
  112.  
  113. </Text>
  114.  
  115. <TouchableOpacity onPress={this.touchDown.bind(this)}>
  116.  
  117. <Text style={[styles.instructions, {backgroundColor: 'green' }]}>
  118.  
  119. test touch me
  120.  
  121. </Text>
  122.  
  123. </TouchableOpacity>
  124.  
  125. </ View >
  126.  
  127. );
  128.  
  129. }
  130.  
  131. // Custom function
  132.  
  133. touchDown() {
  134.  
  135. // console.log console printing, can print values, mostly used for debugging
  136.  
  137. console.log( '>>' , this.isTouchDown);
  138.  
  139. if (!this.state.isTouchDown) {
  140.  
  141. this.setState({
  142.  
  143. text: 'Test Touch Down Success' ,
  144.  
  145. isTouchDown: true  
  146.  
  147. });
  148.  
  149. } else {
  150.  
  151. this.setState({
  152.  
  153. text: 'Test Touch Down Again Success' ,
  154.  
  155. isTouchDown: false  
  156.  
  157. });
  158.  
  159. }
  160.  
  161. }
  162.  
  163. }
  164.  
  165. //Define style
  166.  
  167. const styles = StyleSheet. create ({
  168.  
  169. container: {
  170.  
  171. flex: 1,
  172.  
  173. justifyContent: 'center' ,
  174.  
  175. alignItems: 'center' ,
  176.  
  177. backgroundColor: '#F5FCFF' ,
  178.  
  179. },
  180.  
  181. welcome:
  182.  
  183. fontSize: 20,
  184.  
  185. textAlign: 'center' ,
  186.  
  187. margin: 10,
  188.  
  189. },
  190.  
  191. instructions:
  192.  
  193. textAlign: 'center' ,
  194.  
  195. color: '#333333' ,
  196.  
  197. marginBottom: 5,
  198.  
  199. },
  200.  
  201. });
  202.  
  203. //AppRegistry defines the entry point of the App and provides the root component.
  204.  
  205. //The first 'AwesomeProject' must be consistent with the moduleName registered in AppDelegate
  206.  
  207. //The second AwesomeProject is the entry component, that is, the Component class defined above
  208.  
  209. AppRegistry.registerComponent( 'AwesomeProject' , () => AwesomeProject);

2. Operation effect:

Simple running effect.png

3. Explanation of basic concepts

1) Components

Text, View, and TouchableOpacity in the code are all basic components. AwesomeProject is a self-created component, which also serves as the entry component of the project.

In the React Native project, all displayed interfaces can be regarded as a component, but the complexity of functions and logics is different. Each one is composed of many small components, and each small component has its own corresponding logic.

2) Component status and properties

Components are essentially state machines. If the input is certain, the output must be certain. Components match states with results one by one. Components have state and prop (state and property).

Props are the attributes in the tag. Components pass data through the attributes of the tag, from the parent component to the child component (one-way attribute transfer).

If some states of a component are determined externally and affect the render of the component, then these states should be expressed as props.

For example, the menu items of a drop-down menu component are determined by the user and usage scenario of the component. Therefore, the state of "menu item" should be represented by props and passed in from the outside.

State is the state in a subgroup. Internal event methods or lifecycle methods can call this.setState to change it. When the state changes, the component will also trigger the render function for rendering updates.

If some states of a component need to be changed and will affect the render of the component, then these states should be represented by state.

For example, a shopping cart component will display different prices based on the products and quantities added by the user to the shopping cart. The "total price" state should be represented by state.

<<:  IDE for React Native Development

>>:  WOT2016 Wang Xiuquan: Interpretation of the Difficulties in the Development and Optimization of Mobile Apps

Recommend

Product architecture for e-commerce user growth

As a growth veteran with many years of experience...

Apple to try adding mental health features to iPhone

Apple is working on a series of new programs to h...

Double Eleven e-commerce advertising case!

On the one hand, competition for traffic is inten...

Ranking of 140 information flow platforms, who is the traffic outlet?

As a marketer , we must always pay attention to t...

collect! 10 classic ways to play private community activities

In previous articles, we analyzed the private dom...