[React Native Development] React Native porting nandroid Project

Source: Internet
Author: User

[React Native Development] React Native porting nandroid Project
(1) Preface

In the first three courses, we have explained the React Native For Android environment setup, IDE installation configuration, application running, and debugging knowledge. Today we are talking about a very useful knowledge point. Transplant our existing Native Android project to React Native.

In React Native, React focuses more on the View layer. Therefore, React Native also supports and allows us to easily and conveniently port an Android Native project to React Native.

(2) Prerequisites

①. First, we have an Android Application project built using Gradle. You can directly create a project using Android Studio. Create a directory named TestHello, and use Android Studio to create an android project under the folder. The details are as follows:

②. Node. js must be installed on the computer. The installation and usage (click to enter)

(3) Android project configuration

2.1 Add the React Native dependency to build. gradle of our Android project and synchronize the dependency. The specific code is as follows:

 

compile 'com.facebook.react:react-native:0.17.+'

 

[Note]. this will synchronize react native Versions later than version 0.17. The official version is still in version 0.13 but not updated. My local reactnative version is 0.17, therefore, the configuration must be consistent or updated with your local version. I studied this issue this afternoon and stepped on many pitfalls ~~ However, on the ReactNative Chinese site, I have asked the webmaster to update the version.

2.2 then we need to add the network access permission to AndroidManifest. xml of the project.

This is only used to load the finest JavaScript code from the development server in the development phase. In the official release version, you can delete the network permission if necessary.

(4) add native code

In the MainActivity of the Android project, we need to configure the relevant code to start and run the React Native library. We need to create a ReactRootView, render the React reference in it, and set it to the main view of the Activity.

The Code is as follows:

 

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {    privateReactRootView mReactRootView;    privateReactInstanceManager mReactInstanceManager;     @Override    protectedvoid onCreate(Bundle savedInstanceState) {       super.onCreate(savedInstanceState);        mReactRootView = new ReactRootView(this);       mReactInstanceManager = ReactInstanceManager.builder()               .setApplication(getApplication())               .setBundleAssetName("index.android.bundle")               .setJSMainModuleName("index.android")               .addPackage(new MainReactPackage())               .setUseDeveloperSupport(BuildConfig.DEBUG)               .setInitialLifecycleState(LifecycleState.RESUMED)               .build();       mReactRootView.startReactApplication(mReactInstanceManager, "TestHello",null);        setContentView(mReactRootView);    }     @Override    publicvoid invokeDefaultOnBackPressed() {       super.onBackPressed();    }}

 

Note the following code:

 

mReactRootView.startReactApplication(mReactInstanceManager,"TestHello", null);

 

Here, we use TestHello as the second method parameter. Note that this parameter should be consistent with what we will talk about later. Let's continue to look at the details.

In React Native, FB actually provides us with ReactInstanceManger to manage Activity-related lifecycles for us, so we need to pass some Actitivty-related lifecycles to ReactInstanceManger. The onPause () and onResume () methods are as follows:

 

@Override    protectedvoid onPause() {       super.onPause();         if(mReactInstanceManager != null) {           mReactInstanceManager.onPause();        }    }    @Override    protectedvoid onResume() {       super.onResume();         if(mReactInstanceManager != null) {            mReactInstanceManager.onResume(this,this);        }    }

 

Next, we also need to pass the event that returns the button key:

 

@Override public void onBackPressed() {    if(mReactInstanceManager != null) {       mReactInstanceManager.onBackPressed();    } else {       super.onBackPressed();    }}

 

In this way, the javaScript code can be used when the user presses the return key. Of course, if the front-end does not process the RESPONSE event, it will be called back to the invokeDefaultOnBackPressed () method above. Then the event is rolled back to the Activity. The following figure shows how to execute the Activity and how to execute it. The default event is to close the Activity.

The last step is to process the device menu. By default, you can shake your phone to bring up the menu. However, this method is not applicable to simulators, so we can intercept the event Method and handle it.

 

@Overridepublic boolean onKeyUp(int keyCode, KeyEvent event){    if(keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {       mReactInstanceManager.showDevOptionsDialog();       return true;    }    return super.onKeyUp(keyCode, event);}

 

So far, our Android project Activity and configuration file have completed the most basic configuration methods.

(5) add js

Next we will use the command line to first switch to the project root directory (in my example, switch to the TestHello directory)

. Run npm init on the command line to run the following:

 

This command will create a package. json file and prompt us to enter some information. By default, it is not required, but the name must be in lowercase. The specific result is as follows:

 

. Run npm install -- save react-native on the command line to install the react native module and related node modules. Run the following command:

 

Install the node module and react native module. The node_module folder is generated as follows:

 

. Run the following command:

 

curl -o .flowconfig  https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

 

Configure flow

 

The preceding three steps are complete. The node module is created and the react-native npm dependency is added. Next we need to modify the package. json file and add the following code to the scripts Tag:

 

"start":"node_modules/react-native/packager/packager.sh"

 

The specific modification is as follows:

 

. Now we create a file named index. android. js and add the following code to it:

 

'use strict';var React = require('react-native');var {  Text,  View} = React; class MyAwesomeApp extends React.Component {  render() {    return (     
        
  
   Hello, World
       
     )  }}var styles = React.StyleSheet.create({  container:{    flex: 1,    justifyContent:'center',  },  hello: {    fontSize:20,   textAlign: 'center',    margin:10,  },}); React.AppRegistry.registerComponent('TestHello', ()=> TestHello);

 

The above completes all the relevant code and react-native configuration. Note that TestHello is used above. I hope everyone will use the same name as the previous MainActivity.

(6) run the APP

The above configuration steps are complete. Now we have to run the APP. First, we need to enable the development server and run the following command:

 

npm start

 

The running result is as follows:

 

The next step is the last step. run the react-native run-android command to compile and run the application. The running result is as follows:

 

In this way, a simple Android native project is transplanted to ReactNative.

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.