RN集成到Android原生項目實踐

作者:閒庭CC https://www.jianshu.com/p/f546ad231382

一、Android項目集成RN

1.新建普通Android項目 新建一個普通的Android項目即可,打開Android Studio -> File -> New -> New Project… 按步驟執行即可。

2.在項目根目錄下引入React Native模塊 在AS中的Terminal中輸入npm init ,輸入一些項目的描述屬性(默認一路回車也行),爲了生成·文件的項目描述,根據提示來填寫就好了,生成的json文件內容大致如下:

{
      "name": "rnappdemo",
      "version": "1.0.0",
      "description": "test",
      "main": "index.js",
      "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "no"
      },
      "repository": {
        "type": "git",
        "url": "no"
      },
      "keywords": [
        "no"
      ],
      "author": "liu",
      "license": "ISC",
      "dependencies": {
        "react": "^16.5.2",
        "react-native": "^0.55.4"
      }
    }

3.引入rn的一些模塊文件

npm install --save react react-native

會在根目錄生成一個node_modules文件夾,存的是RN的一些模塊文件,如果在這個過程中出現require react@某.某.某版本, but none was installed ,那麼就使用命令 npm i -S react@某.某.某版本//此處爲提示的版本號. 注意:如何安裝React Native指定版本,命令如:npm install --save [email protected] ,這裏建議使用因爲最新版本使用可能會出錯,稍微比新版低個版本,我這裏沒用最新版,使用的是0.55.4。 如何查看當前rn版本信息:npm info React-native

4.引入.flowconfig文件

方法一:.flowconfig文件可以從facebook的github上覆制,然後在工程的根目錄創建.flowconfig文件,將其內容複製進去即可。 方法二:在Terminal中執行以下命令:

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

5.接下來打開package.json文件,在scripts模塊下添加,如上步驟2顯示。 "start": "node node_modules/react-native/local-cli/cli.js start"

6.在項目根目錄下的build.gradle添加以下配置

allprojects {
      repositories {
          jcenter()
          maven {
              url "https://maven.google.com"
          }
          maven {
              // All of React Native (JS, Android binaries) is installed from npm
              url "$rootDir/node_modules/react-native/android"//此處目錄請額外注意
          }
      }
  }

7.在app下的build.gradle -> dependencies 添加以下依賴:

compile "com.facebook.react:react-native:+" // From node_modules.

同時在android -> defaultConfig 中添加 ndk{ abiFilters "armeabi-v7a","x86"} 完整如下:

   defaultConfig {
            applicationId "com.liujc.rnappdemo"
            minSdkVersion 16
            targetSdkVersion 27
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            ndk{
                abiFilters "armeabi-v7a","x86"
            }
        }

8.在 AndroidManifest.xml 清單文件中聲明網絡權限:

<uses-permission android:name="android.permission.INTERNET" />

如果需要訪問 DevSettingsActivity 界面(即開發者菜單),則還需要在 AndroidManifest.xml 中聲明:

<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

二、編寫RN代碼運行到Android項目中

1.在根目錄下創建index.android.js文件:

'use strict';
import React, { Component } from 'react';
import {
 AppRegistry,
 StyleSheet,
 Text,
 NativeModules,
 View,
 ToastAndroid,
 DeviceEventEmitter
} from 'react-native';
let title = 'React Native界面';

class reactNative extends Component {

/**加載完成*/
componentWillMount() {
  let result = NativeModules.MyNativeModule.Constant;
  console.log('原生端返回的常量值爲:' + result);
}

/**
* 原生調用RN
*/
componentDidMount() {
   DeviceEventEmitter.addListener('nativeCallRn',(msg)=>{
        title = "React Native界面,收到數據:" + msg;
        ToastAndroid.show("發送成功", ToastAndroid.SHORT);
   })
}
render() {
return (
  <View style={styles.container}>
    <Text style={styles.welcome} >
        {title}
    </Text>

    <Text style={styles.instructions}>
      To get started, edit index.android.js
    </Text>

    <Text style={styles.instructions}>
      Double tap R on your keyboard to reload,{'\n'}
      Shake or press menu button for dev menu
    </Text>

    <Text style={styles.welcome}>
      我是RN界面!
    </Text>
  </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,
 },
});   
AppRegistry.registerComponent('reactNative', () => reactNative);

2.在Terminal中執行啓動命令 npm run start 或者 yarn start//默認啓動端口爲8081,後面會描述如何修改端口號. 啓動完成後出現如下界面:

┌──────────────────────────────────────────────   ────────────────────────────────┐
│                                                                              │
│  Running Metro Bundler on port 8081.                                         │
│                                                                              │
│  Keep Metro running while developing on any JS projects. Feel free to   
│
│  close this tab and run your own Metro instance if you prefer.               │
│                                                                              │
│  https://github.com/facebook/react-native                                    │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

Looking for JS files in
E:\workspace\WsForRN\RNAppDemo\RNAppDemo

Metro Bundler ready.

Loading dependency graph, done.

然後在瀏覽器中輸入http://localhost:8081/index.android.bundle 訪問沒有報錯,則說明啓動成功.

3.在Application裏面添加如下代碼:

public class AppApplication extends Application implements ReactApplication {
 private static AppApplication instance;
 @Override
 public void onCreate() {
     super.onCreate();
     instance = this;
     SoLoader.init(this, false);
 }

 private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

     @Override
     public boolean getUseDeveloperSupport() {
         return BuildConfig.DEBUG;
     }

     @Override
     protected List<ReactPackage> getPackages() {
         return Arrays.<ReactPackage>asList(
                 new MainReactPackage()
         );
     }
 };

 /**
  * 獲取Application實例
  */
 public static AppApplication getInstance() {
     return instance;
 }
 @Override
 public ReactNativeHost getReactNativeHost() {
     return mReactNativeHost;
 }
}

4.在對應Activity中添加如下代碼:

public class MyRNActivity extends ReactActivity {
 @Override
 protected String getMainComponentName() {
     return "reactNative";//此處容器名要與index.android.js裏面註冊的控件名一致
 }
}

5.記得把Application和對應的Activity在AndroidManifest.xml中註冊使用。運行APP即可加載RN界面。 備註:設備要和服務端在同一局域網下調試,即鏈接同一WiFi或者設備鏈接電腦的代理。

— — — END — — —

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章