本文的記錄适合已經按照 React-Native 中文網搭建好環境并且能夠成功運作 Hello World 的 React-Native 原生項目的同學。文末會放上 github 的位址。
各種環境的搭建參照 React-Native中文網,環境搭建好後就可以開始了。
1. 打開 AS ,建立一個原生項目,這裡項目名為 RNDemo
2.在 AS 終端中輸入指令
npm init
接下來按照提示輸入對應資訊,有的可以不填,如圖:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX6lEVNxmWXF2cOdVY6ZFWiZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zNzMTOwIDM1ETMzgDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
**這裡注意,名字不能有大寫字母!
初始化完成後就會在項目根目錄下生成一個 package.json 檔案。打開檔案,在 scripts{} 裡添加如下部分,用于之後啟動 packager:
"start": "node node_modules/react-native/local-cli/cli.js start"
**注意兩行之間要有逗号。
檔案整體如下:
{
"name": "rnapp",
"version": "1.0.0",
"description": "This is my first RN-App!",
"main": "index.android.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"author": "yq",
"license": "ISC"
}
2. 終端輸入指令:
npm install --save react react-native
有一個等待的過程,完成後會在項目根目錄下生成一個 node_modules 檔案夾,檔案夾裡的内容就是執行指令所下載下傳的,如圖所示:
但是終端會有一些警告,如圖:
按照提示安裝對應版本,指令如下:
npm install --save [email protected] [email protected]
3. 在項目根目錄 build.gradle 檔案的 allprojects{} (注意是:allprojects 裡)添加如下位址:
maven{
url "$rootDir/node_modules/react-native/android"
}
添加完後是這樣的:
allprojects {
repositories {
jcenter()
maven{
url "$rootDir/node_modules/react-native/android"
}
}
}
然後在 app 目錄下的 build.gradle 裡添加依賴:
compile 'com.facebook.react:react-native:+'
同步項目,會報如下的錯誤:
Error:Conflict with dependency 'com.google.code.findbugs:jsr305' in project ':app'. Resolved versions for app (3.0.0) and test app (2.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
在 app/bulid.gradle 檔案的 android{} 子產品裡添加
configurations.all {
//for Error:Conflict with dependency 'com.google.code.findbugs:jsr305'
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
同步項目,上面的問題解決了,但是又有新的錯誤,如下:
Manifest merger failed : uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library [com.facebook.react:react-native:0.47.2]
C:\Users\yinqi.android\build-cache\1db15acba046d1d8bc220e7717d1e2ffd328aad6\output\AndroidManifest.xml
這個還是能看的明白的,最低版本不能低于16,那我們就修改最低支援版本為16,修改後在同步項目 ok 了。
解決了錯誤,還要确認下下載下傳到的 react-native 依賴包的版本是否是 0.47.2,如果不是 0.47.2 而是0.20.1,說明上面的 maven 位址配置的可能有問題。
3. 在項目根目錄下建立 index.android.js (這裡的檔案名要和第一步輸入的那個package name 對應的名字一樣)檔案,加入如下代碼:
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
//hello world 對應代碼
class HelloWorld extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.hello}>Hello, World!\nThis is my first rnApp!</Text>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: ,
justifyContent: 'center',
},
hello: {
fontSize: ,
color:'red',
textAlign: 'center',
margin: ,
},
});
//這裡的 rnapp 可以和項目的名字不一樣
AppRegistry.registerComponent('rnapp', () => HelloWorld);
4. 建立用于加載 index.android.js 的 Activity,要實作 DefaultHardwareBackBtnHandler 接口,代碼如下:
package com.yq.rndemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
public class RNActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")//bundle 的名字
.setJSMainModuleName("index.android")//js 檔案的名字
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(true)//開發者模式
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "rnapp", null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause(this);
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(this);
}
}
@Override
public void onBackPressed() {
// if (mReactInstanceManager != null) {
// mReactInstanceManager.onBackPressed();
// } else {
// }
super.onBackPressed();
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
}
5. 添權重限并注冊 RN 的設定界面, manifest檔案如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yq.rndemo">
<uses-permission android:name="android.permission.INTERNET" />
<!--懸浮窗-->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:name=".RNApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RNActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
<!-- React-Native 設定界面-->
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
最後在 MainActivity 中加入跳轉到 RNActivity 的按鈕,原生項目嵌入 React-Native 就完成了,接下來就是運作項目看是否能成功。
5.首先啟動 package server ,指令如下:
npm start
看到 Loading dependency graph, done. 就是啟動成功了。
然後安裝 app 到手機,指令如下:
gradlew installDebug
運作 app 跳轉到 RNActivity 界面,有時候可能不會顯示,這時候就要配置調試端口再 Reload了,直接 Reload 會提示:
端口配置步驟如下:
手機菜單(Menu)按鍵 –> Dev Setting –> Debugging 下的 Debug server host & port for device,點選輸入 192.168.1.xxx:8081 就可以了。
** 注:手機要和電腦在同一區域網路下。
這時候傳回點選手機菜單鍵再次 Reload 就可以了;如果不行,傳回重新進入頁面。
6.另外需要注意的兩點
(1)調試需要懸浮窗權限,如果 app target設定為 23 以上,手機系統版本為 6.0 以上并且沒有動态申請權限的話,一定要記得手動開啟懸浮窗權限;
(2)在調試過程中 packger 必須要保證運作狀态,否則進行 Reload 操作的時候會報錯誤,如圖:
補充:加載 index.android.js 的 Activity 的另一種寫法:
1. 繼承 ReactActivity ,重寫 getMainComponentName 方法,傳回值為 js 檔案中注冊的名字(demo 中為 ‘rnapp’),代碼如下:
package com.yq.rndemo;
import com.facebook.react.ReactActivity;
public class MyReactActivity extends ReactActivity {
@Override
protected String getMainComponentName() {
return "rnapp";
}
}
(2) 自定義 Application 類,實作 ReactApplication 接口(上面那種方法不需要),否則會報錯:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yq.rndemo/com.yq.rndemo.MyReactActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.facebook.react.ReactApplication
具體代碼如下:
package com.yq.rndemo;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
/**
* Created by yinqi on 2017/8/31.
*/
public class RNApplication extends Application implements ReactApplication {
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()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
(3)不要忘了在 manifest 中注冊:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yq.rndemo">
<uses-permission android:name="android.permission.INTERNET" />
<!--懸浮窗-->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
<!--繼承 ReactActivity 注意:實際在 manifest 中這一行要删除,否則報錯-->
android:name=".RNApplication"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--實作 DefaultHardwareBackBtnHandler 接口-->
<activity
android:name=".RNActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar" />
<!--繼承 ReactActivity-->
<activity
android:name=".MyReactActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"></activity>
<!-- React-Native 設定界面-->
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
</manifest>
最後,打正式包:
首次在 app/src/main 目錄下建立 assets 檔案夾,然後終端在項目根目錄下執行指令:
react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output app/src/main/assets/index.android.bundle --assets-dest app/src/main/res/