Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

React Native 整合進既有專案:完整步驟與踩坑修復紀錄

編輯:關於 Android 程式設計

前言

React Native 已經存在一段時間,不少團隊都在評估導入。前面幾篇說明了如何從零建立 RN 專案、如何架好原生與 JS 的開發環境,但真實世界的專案往往不是從零開始的——多半是要把 RN 塞進一個已經上線、已經有幾十個頁面的既有 App 裡試水溫。本文記錄這個過程。

目標

用 Android Studio 建一個專案,首頁放一顆按鈕,點下去跳到一個由 React Native 實作的頁面。就這樣,最小可行的驗證。

建立 Android 專案

RN 官方支援的最低版本是 Android 4.1(API 16),因此最小 SDK 直接設為 16。

Supported operating systems are >= Android 4.1 (API 16) and >= iOS 7.0.

專案建好後先加一顆按鈕,此時還不能跳轉,只是先彈個 Toast:

findViewById(R.id.to_react).setOnClickListener(v ->
        Toast.makeText(MainActivity.this, "go to React", Toast.LENGTH_LONG).show());

整合步驟

以下依官方文件順序進行。開始之前請確認 Node.js、watchman 等環境已就緒。

1. 初始化 npm

在專案根目錄執行:

npm init

這會產生 package.json。過程中會詢問 name,這裡填的名字之後會成為 JS 端的元件註冊名稱,必須前後一致。注意 npm 的套件名只能小寫:

name: (RNDemo1) rndeme1
version: (1.0.0) 1.0.0
description: deme
entry point: (index.js) index.android.js
...
Is this ok? (yes)

2. 安裝 node module

npm install --save react react-native

執行完會在根目錄產生 node_modules。這一步也可以直接從既有專案複製過來,省下等待時間。

3. 建立 .flowconfig

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

flow 是靜態型別檢查工具,這個設定檔是隱藏檔,macOS 下用 ls -al 才看得到。

4. 修改 package.json

在 scripts 節點下加入啟動指令:

{
  "name": "rndeme1",
  "version": "1.0.0",
  "main": "index.android.js",
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "test"
  },
  "dependencies": {
    "react": "^15.3.2",
    "react-native": "^0.35.0"
  }
}

可以看到安裝 node module 時,依賴已被自動寫入。

5. 建立 index.android.js

'use strict';

import React from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';

class HelloWorld extends React.Component {
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.hello}>Hello, World</Text>
            </View>
        );
    }
}

var styles = StyleSheet.create({
    container: { flex: 1, justifyContent: 'center' },
    hello: { fontSize: 20, textAlign: 'center', margin: 10 },
});

AppRegistry.registerComponent('rndeme1', () => HelloWorld);

唯一要改的是 registerComponent() 的第一個參數,必須與 package.json 的 name 相同。

6. 修改 Gradle

Android 專案靠 Gradle 構建,所以要改兩處。app 模組的 build.gradle 加入依賴:

dependencies {
    // ...
    compile "com.facebook.react:react-native:+"
}

根目錄的 build.gradle 加入本地 maven 倉庫,放在 allprojects 底下:

allprojects {
    repositories {
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

7. 加權限

開發階段 JS bundle 是從本機 packager 拉取的,必須有網路權限,因此在 AndroidManifest.xml 中補上 android.permission.INTERNET。

加入原生入口

新增一個 Activity 承載 RN 畫面:

public class MyReactActivity extends Activity
        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")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "rndeme1", null);
        setContentView(mReactRootView);
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }
}

主題要設為 @style/Theme.AppCompat.Light.NoActionBar,因為部分 RN 元件依賴這個主題。另外記得把首頁的 Toast 換成啟動這個 Activity:

Intent intent = new Intent();
intent.setClass(MainActivity.this, MyReactActivity.class);
startActivity(intent);

填坑記錄

官方步驟做完,跑起來——如預期地失敗了,而且連續失敗。以下依序記錄。

坑一:java.lang.UnsatisfiedLinkError

Caused by: java.lang.UnsatisfiedLinkError:
could find DSO to load: libreactnativejni.so
    at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:213)

找不到對應 ABI 的 so 檔。在 app 的 build.gradle 的 defaultConfig 下補上 ndk 節點:

defaultConfig {
    ndk {
        abiFilters "armeabi-v7a", "x86"
    }
}

坑二:NDK integration is deprecated

Error:(13, 0) NDK integration is deprecated in the current plugin.
Consider trying the new experimental plugin

兩種解法擇一:在 gradle.properties 中加入 android.useDeprecatedNdk=true,或是降低 Gradle 版本。

坑三:java.lang.IllegalAccessError

Caused by: java.lang.IllegalAccessError: Method
'void android.support.v4.net.ConnectivityManagerCompat.<init>()'
is inaccessible to class
'com.facebook.react.modules.netinfo.NetInfoModule'

support-v4 的版本與 RN 預期不符。解法是把 maven 路徑寫法改成正確的相對路徑:

// 改為
url "$rootDir/node_modules/react-native/android"

路徑變了之後,Android Studio 中相關的 import 需要重新整理。

坑四:Application HelloWorld has not been registered

這次沒有錯誤 log,但畫面出現紅色錯誤框:

原因是我們直接複製了範例程式碼,卻忘了改名:

mReactRootView.startReactApplication(mReactInstanceManager, "rndeme1", null);
//                                                             ^^^^^^^^^ 原本是 "HelloWorld"

注意:package.json 的 name、index.android.js 的 registerComponent 參數、Activity 中的 startReactApplication 參數,這三處名稱必須完全一致。

改完再跑,終於成功:

把 JS 中的文字改成 "Native Hello World",存檔後搖一搖手機選 Reload,畫面立刻更新——這一刻才算真正打通了「改 JS 即時看效果」的開發迴路。

其他常見狀況

  • 搖手機沒反應:部分系統會攔截浮動視窗,需手動開啟「在其他應用程式上層顯示」權限。
  • 連線失敗:手機與電腦必須在同一網段;實機連不到時可用 adb reverse tcp:8081 tcp:8081 繞過網路問題。
  • 點 Dev Setting 崩潰:需在 AndroidManifest.xml 中補上 <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />。

總結

把 RN 整合進既有專案,主線步驟其實只有六步:npm init → 裝 react/react-native → 補 .flowconfig → 改 package.json 加 start 指令 → 寫 index.android.js → 改兩處 Gradle 並加網路權限。真正耗時間的是那串編譯與執行期錯誤,而它們幾乎都源自同一類問題:版本搭配與名稱一致性。

最後補一個實務建議:正式上線時,開發階段用的 packager 不會存在,必須把 JS bundle 打包進 assets。做法是執行 react-native bundle --platform android --dev true --entry-file index.android.js --bundle-output app/src/main/assets/index.android.bundle --assets-dest app/src/main/res/,並把 setUseDeveloperSupport() 設為 false。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved