Getting started with React Native Android and in-depth source code analysis series (1) -- Hello world

Source: Internet
Author: User

Getting started with React Native Android and in-depth source code analysis series (1) -- Hello world

From today on, I will analyze the source code of React Native for Android.

This series analyzes React Native Android step by step from the perspective of usage and source code analysis. Of course, because I don't know much about IOS, I can only analyze android.

First, let's get a Hello world.

I will not introduce the development environment of Rn Android here because of the idea of not repeating the wheel.

1. Create a project

First, create an Rn project and run the following command:

 

react-native init AweSomeProject

Then go to the project directory. Select the android directory:

 

 

Check that the build. gradle file is in the file. We can run android through react-native run-android. However, we choose to use AndroidStudio for subsequent development.

Select the android directory when importing the project. Then the project is imported. Wait for a long gradle update process. At this time, it seems that tianchao needs vpn.

 

After waiting, click run to run the program. We assume that you have already created a virtual phone on your computer. Let's talk about it later. Because it is a little complicated.

 

At this time, you can see that the mobile phone actually has an effect.

 

2. MainActivity Analysis

At this time, the project has created a MainActivity by default. Let's analyze its source code:

public class MainActivity extends ReactActivity {    /**     * Returns the name of the main component registered from JavaScript.     * This is used to schedule rendering of the component.     */    @Override    protected String getMainComponentName() {        return "AwesomeProject";    }    /**     * Returns whether dev mode should be enabled.     * This enables e.g. the dev menu.     */    @Override    protected boolean getUseDeveloperSupport() {        return BuildConfig.DEBUG;    }   /**   * A list of packages used by the app. If the app uses additional views   * or modules besides the default ones, add more packages here.   */    @Override    protected List
 
   getPackages() {      return Arrays.
  
   asList(        new MainReactPackage(),              new ToastReactPackage()      );    }}
  
 
The English comments are clearly explained. In fact, the most important part of our custom module is to add the modules we need to register in the getPackages () method. For example, ToastReactPackage is registered here. This will be said.

3. index. android. js File

Let's look back at the js file. Open this file and the default one is available. But I am not satisfied with it. Let's make a simple album.

/*** Sample React Native App * https://github.com/facebook/react-native */'use strict '; import React, {AppRegistry, Component, StyleSheet, Text, View, Image} from 'react-native '; import KankanToast from '. /androidview/ToastAndroid; var imgs = ['HTTP: // response, 'HTTP: // www.ituring.com.cn/bookcover/1668.553.jpg', 'HTTP: // your MyImage = React. createClass ({getInitialState: function () {return {imgs: imgs, count: 0 };}, goNext: function () {var count = this. state. count; count ++; if (count  = 0) {this. setState ({count: count}) ;}, render: function () {return (<view style = "{styles. flex} "> <view style =" {styles. image} ">  </view> <view style = "{styles. btns} "> <touchableopacity data-cke-pa-onpress =" {this. goPreview} "> <view style =" {styles. btn} "> <text> Prev </text> </view> </touchableopacity> <touchableopacity data-cke-pa-onpress =" {this. goNext} "> <view style =" {styles. btn} "> <text> Next </text> </view> </touchableopacity> </view>) ;}}; KankanToast. show ('this is a Toast ', KankanToast. SHORT); class AwesomeProject extends Component {render () {return (<view style = "{styles. container} "> <myimage> </view>) ;}} 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,}, image: {borderWidth: 1, width: 300, height: 200, borderRadius: 5, borderColor: '# ccc', justifyContent: 'center', alignItems: 'center'}, img: {height: 150, width: 200}, btns: {flexDirection: 'row', justifyContent: 'center', marginTop: 20}, btn: {width: 60, height: 30, borderColor: '# 0089FF', borderWidth: 1, justifyContent: 'center', alignItems: 'center', borderRadius: 3, marginRight: 20}); AppRegistry. registerComponent ('awesomeproject', () => AwesomeProject );

We can't wait to take a look at the effect:

I posted a Toast, but you can see if it is a moyang with the original ecology of Android. Oh, look. In fact, moyang's name is really nice.

Then we came up with our desired album. Is it ugly? Let's just look at it. You can do it. No, don't force it.

 

Let's analyze the meaning of this source code.

This code is all JavaScript code. Let's explain the meaning of the Code.

1) import:

Import React ,{
AppRegistry,
Component,
StyleSheet,
Text,
View,
Image
} From 'react-native ';
The above describes how to import the corresponding modules from the react-native library.

Import KankanToast from './androidview/toastandroid ';

 

This is interesting. This is to import the ToastAndroid module from the androidview subdirectory in the current directory. It is actually the./androidview/ToastAndroid. js file. Its content will be discussed later

2. Define Arrays
Var imgs = [
'Http: // www.ituring.com.cn/bookcover/1442.796.jpg ',
'Http: // www.ituring.com.cn/bookcover/1668.553.jpg ',
'Http: // www.ituring.com.cn/bookcover/1521.260.jpg'
];

This array is used to store image paths.

3. Define a UI control

Var MyImage = React. createClass ({...});

This is our far-reaching album control.

4. A Toast is displayed.

KankanToast. show ('this is a Toast ', KankanToast. SHORT );

As you can see, I use KankanToast, a component defined by myself. As for why KankanToast is used, it is mainly because Zeng is a senior developer of Xunlei.

Of course, we changed our name to xiangchao, xiangchao, and xiangchao. The important thing is three times. If you don't remember it, I will send you an iQiYi membership card.

5. program entry Components

Class AwesomeProject extends Component

This contains a render function. Note that only one root node can exist.

6. Define css styles

Const styles = StyleSheet. create

You don't need to talk about this.

7. register the program entry component


AppRegistry. registerComponent ('awesomeproject', () => AwesomeProject );

Here we have finished the js Code. Let's look back at what happened to our KankanToast.

Of course, you 'd better comment it out. It's too late to go to bed. Don't ask why, I have a low salary and are willful.

Good night. Next, custom controls.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.