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: - //Command line to create a project:
-
- 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: - #import "AppDelegate.h"
-
- // React Native related header files
-
- #import "RCTBundleURLProvider.h"
-
- #import "RCTRootView.h"
-
- @implementation AppDelegate
-
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
-
- {
-
- NSURL *jsCodeLocation;
-
- /*
-
- 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)
-
- This re-invokes the terminal window you opened when running the app, which starts a packager and server to handle the above request.
-
- Open that URL in Safari; you’ll see the app’s JavaScript code.
-
- */
-
- [[RCTBundleURLProvider sharedSettings] setDefaults];
-
- jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@ "index.ios" fallbackResource:nil];
-
- // 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.
-
- RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
-
- moduleName:@ "AwesomeProject"
-
- initialProperties:nil
-
- launchOptions:launchOptions];
-
- rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
-
- self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
-
- UIViewController *rootViewController = [UIViewController new];
-
- rootViewController.view = rootView ;
-
- self.window.rootViewController = rootViewController;
-
- [self.window makeKeyAndVisible];
-
- return YES;
-
- }
-
- @ 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. - NSArray *imageList = @[@ "http://foo.com/bar1.png" ,
-
- @ "http://foo.com/bar2.png" ];
-
- NSDictionary *propsDict = @{@ "images" : imageList};
-
- RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
-
- moduleName:@ "AwesomeProject"
-
- initialProperties: propsDict
-
- 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) - NSArray *imageList = @[@ "http://foo.com/bar3.png" ,
-
- @ "http://foo.com/bar4.png" ];
-
- rootView.appProperties = @{@ "images" : imageList};
2. Parse the js entry file (index.ios.js) 1. The index.ios.js code is as follows: - 'use strict' ; // Globally enter strict mode (currently found that it is not necessary)
-
- /**<
-
- Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors;
-
- Eliminate some insecurity in code operation and ensure the safety of code operation;
-
- Improve compiler efficiency and increase running speed;
-
- Pave the way for future new versions of Javascript.
-
- */
-
- //Import some necessary modules
-
- // React Native built-in components can be directly imported via { xxx } from 'react-native' to import, of course, you can also customize the components.
-
- import React, { Component } from 'react' ;
-
- import {
-
- AppRegistry,
-
- StyleSheet,
-
- Text,
-
- View ,
-
- TouchableOpacity
-
- } from 'react-native' ;
-
- //Class, this is the default loading class, inherited from Component, Component class (component) is similar to View in Android and iOS
-
- //Here is a component
-
- class AwesomeProject extends Component {
-
- //Constructor, each component has its own properties (props) and state (state)
-
- //When calling this.setState to change the state text or isTouchDown, the component will trigger the render function to render and update
-
- constructor(props) {
-
- super(props);
-
- this.state = {
-
- text: 'Welcome to React Native!' ,
-
- isTouchDown: false
-
- };
-
- }
-
- //Called once before the initial rendering, where preprocessing operations can be performed
-
- //In React, setting this.state will cause re-rendering, but setting this.state in componentWillMount will not cause render to be called multiple times
-
- //The component life cycle will be further explained later
-
- componentWillMount() {
-
- }
-
- //Rendering function, used to render the actual visible part of the Component
-
- render() {
-
- //var defines variables and changes the corresponding values according to the status values
-
- var welcomeText = this.state.text;
-
- var bgcolor;
-
- if (this.state.isTouchDown) {
-
- bgcolor = '#c5c5ab' ;
-
- } else {
-
- bgcolor = '#F5FCFF' ;
-
- }
-
- console.log( 'testtststststts' );
-
- //The returned content is displayed on the interface
-
- return (
-
- < View style={[styles.container, {backgroundColor: bgcolor}]}>
-
- <Text style={styles.welcome}>
-
- {welcomeText}
-
- </Text>
-
- <Text style={styles.instructions}>
-
- To get started, edit index .android.js
-
- </Text>
-
- <Text style={styles.instructions}>
-
- Shake or press menu button for dev menu
-
- </Text>
-
- <TouchableOpacity onPress={this.touchDown.bind(this)}>
-
- <Text style={[styles.instructions, {backgroundColor: 'green' }]}>
-
- test touch me
-
- </Text>
-
- </TouchableOpacity>
-
- </ View >
-
- );
-
- }
-
- // Custom function
-
- touchDown() {
-
- // console.log console printing, can print values, mostly used for debugging
-
- console.log( '>>' , this.isTouchDown);
-
- if (!this.state.isTouchDown) {
-
- this.setState({
-
- text: 'Test Touch Down Success' ,
-
- isTouchDown: true
-
- });
-
- } else {
-
- this.setState({
-
- text: 'Test Touch Down Again Success' ,
-
- isTouchDown: false
-
- });
-
- }
-
- }
-
- }
-
- //Define style
-
- const styles = StyleSheet. create ({
-
- container: {
-
- flex: 1,
-
- justifyContent: 'center' ,
-
- alignItems: 'center' ,
-
- backgroundColor: '#F5FCFF' ,
-
- },
-
- welcome:
-
- fontSize: 20,
-
- textAlign: 'center' ,
-
- margin: 10,
-
- },
-
- instructions:
-
- textAlign: 'center' ,
-
- color: '#333333' ,
-
- marginBottom: 5,
-
- },
-
- });
-
- //AppRegistry defines the entry point of the App and provides the root component.
-
- //The first 'AwesomeProject' must be consistent with the moduleName registered in AppDelegate
-
- //The second AwesomeProject is the entry component, that is, the Component class defined above
-
- 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. |