簡述RN整合到Android原生專案
最近一段時間比較忙,也沒時間梳理下自己的學習筆記,隔了好久也不知道要整理些什麼出來,剛好最近在整理下React Native相關的東東,
所以在此記錄下留作筆記使用。(在這就不描述Android專案和RN專案環境如何搭建了。)
一、Android專案整合RN
-
新建普通Android專案
新建一個普通的Android專案即可,開啟
Android Studio
->File
->New
->New Project...
按步驟執行即可。 -
在專案根目錄下引入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" } }
-
引入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
-
引入.flowconfig檔案
-
接下來開啟package.json檔案,在scripts模組下新增,如上步驟2顯示。
"start": "node node_modules/react-native/local-cli/cli.js start"
-
在專案根目錄下的
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"//此處目錄請額外注意 } } }
-
在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" } }
-
在
AndroidManifest.xml
清單檔案中宣告網路許可權:<uses-permission android:name="android.permission.INTERNET" />
如果需要訪問 DevSettingsActivity 介面(即開發者選單),則還需要在
AndroidManifest.xml
中宣告:<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
二、編寫RN程式碼執行到Android專案中
-
在根目錄下建立
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);
-
在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
訪問沒有報錯,則說明啟動成功. -
在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; } }
-
在對應Activity中新增如下程式碼:
public class MyRNActivity extends ReactActivity { @Override protected String getMainComponentName() { return "reactNative";//此處容器名要與index.android.js裡面註冊的控制元件名一致 } }
-
記得把Application和對應的Activity在AndroidManifest.xml中註冊使用。執行APP即可載入RN介面。
備註:裝置要和服務端在同一區域網下除錯,即連結同一WiFi或者裝置連結電腦的代理。
到此僅記錄Android原生整合RN專案的方法,即初級技能,稍後整理下稍微升級點的技能,清單如下:
- 手動修改React Native埠號
- 將RN專案打包成離線包
- RN與Android原生的訊息通訊
- RN使用Android原生控制元件或者自定義元件
- RN預載入實現
- React Native Linking與 Android原生頁面路由跳轉實現
- RN專案拆包和熱更新