React Native組件集成到Android原生項(xiàng)目
為了把 React Native 集成到 Android 原生項(xiàng)目中,踩了很多坑,因?yàn)樽鳛閣eb前端開發(fā),本來(lái)就不熟悉安卓,參考了網(wǎng)上很多文章,但是都很舊了,而 React Native 已經(jīng)升級(jí)到了 0.55 版本了,入口文件已經(jīng)合成了一個(gè) index.js,下面的內(nèi)容也是基于這個(gè)版本實(shí)踐的。
環(huán)境搭建
已經(jīng)搭建好 React Native 環(huán)境的可以跳過(guò),還沒(méi)有的可以參考 React Native 中文網(wǎng)的 搭建教程,比較詳細(xì)。
創(chuàng)建Android原生項(xiàng)目
安卓開發(fā)者自然很熟悉這個(gè)步驟,然而對(duì)于web前端開發(fā)者還是比較迷茫的??梢詤⒖家幌?使用Android Studio創(chuàng)建一個(gè)新的Android工程,創(chuàng)建一個(gè) Empty Activity,接下來(lái)會(huì)比較好操作。
集成React Native
步驟一:安裝相關(guān)依賴
在項(xiàng)目根目錄下執(zhí)行 npm init 命令,生成 package.json 文件,添加以下命令
- "scripts": {
- "start": "node node_modules/react-native/local-cli/cli.js start"
- }
執(zhí)行 npm i react react-native -S 安裝 react 和 react-native
步驟二:配置maven
在你的 app/ 目錄下的 build.gradle 文件中的 dependencies 里添加 React Native 依賴:
- dependencies {
- ...
- compile "com.facebook.react:react-native:+"
- }
在項(xiàng)目根目錄下的 build.gradle 文件中為 React Native 添加一個(gè) maven 依賴的入口,必須寫在 “allprojects” 代碼塊中:
- allprojects {
- repositories {
- ...
- maven {
- url "$rootDir/node_modules/react-native/android"
- }
- }
- }
步驟三:代碼集成,創(chuàng)建我們的 react-native 組件,在根目錄下創(chuàng)建 index.js,(在 react-native 0.49.0版本以前,是 index.android.js 和 index.ios.js 作為入口文件,現(xiàn)在合成一個(gè) index.js 文件了)
- import React, {Component} from 'react';
- import {AppRegistry,View,Text} from 'react-native';
- class App extends Component{
- render(){
- return (
- <View>
- <Text>哈哈哈</Text>
- </View>
- )
- }
- }
- AppRegistry.registerComponent('ReactNativeView', () => App);
然后創(chuàng)建 MyReactActivity,Activity 是安卓中基本的頁(yè)面單元,簡(jiǎn)單的說(shuō),可以看做 web 開發(fā)中的一個(gè) html 頁(yè)面。
在上面創(chuàng)建安卓項(xiàng)目的時(shí)候,已經(jīng)創(chuàng)建了一個(gè) MainActivity,在它的同級(jí)目錄下,在 Android Studio右鍵新建一個(gè) Activity,命名為 MyReactActivity,然后把內(nèi)容改為如下:
- package com.example.administrator.androidreactnative;
- import javax.annotation.Nullable;
- import com.facebook.react.ReactActivity;
- public class MyReactActivity extends ReactActivity {
- @Nullable
- @Override
- protected String getMainComponentName() {
- return "ReactNativeView";
- }
- }
接著創(chuàng)建 MainApplication
- package com.example.administrator.androidreactnative;
- 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;
- public class MainApplication 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,false);
- }
- }
***在 app/src/main/AndroidManifest.xml 文件中,添加一些權(quán)限,以及聲明MainApplication 跟 MyReactActivity
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.administrator.androidreactnative">
- <uses-permission android:name="android.permission.INTERNET"/> <!-- 網(wǎng)絡(luò)權(quán)限 -->
- <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> <!-- 彈框權(quán)限 -->
- <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW"/> <!-- 窗體覆蓋權(quán)限 -->
- <!-- 聲明MainApplication -->
- <application
- android:name=".MainApplication"
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:roundIcon="@mipmap/ic_launcher_round"
- 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>
- <!-- 聲明MyReactActivity -->
- <activity
- android:name=".MyReactActivity"
- android:label="@string/app_name"
- android:theme="@style/AppTheme">
- </activity>
- <!-- 聲明可以通過(guò)晃動(dòng)手機(jī)或者點(diǎn)擊Menu菜單打開相關(guān)的調(diào)試頁(yè)面 -->
- <activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
- </application>
- </manifest>
原生頁(yè)面跳轉(zhuǎn)到react-native頁(yè)面
在 MainActivity 添加一個(gè)按鈕跳轉(zhuǎn)到 MyReactActivity,首先在 app/src/main/res/layout 下的 activity_main.xml 添加一個(gè)按鈕元素
- <Button
- android:id="@+id/btn"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="點(diǎn)擊跳轉(zhuǎn)到RN界面"/>
然后在 MainActivity 里添加點(diǎn)擊跳轉(zhuǎn)事件
- package com.example.administrator.androidreactnative;
- import android.support.v7.app.AppCompatActivity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- public class MainActivity extends AppCompatActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // 點(diǎn)擊按鈕跳轉(zhuǎn)到 react-native 頁(yè)面
- findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- startActivity(new Intent(MainActivity.this,MyReactActivity.class));
- }
- });
- }
- }
然后在Android Studio 的模擬器中打開就可以看到以下頁(yè)面:
同時(shí)執(zhí)行 npm start 啟動(dòng)本地服務(wù)器,點(diǎn)擊按鈕,出現(xiàn)了紅屏,也就是錯(cuò)誤頁(yè)面。
從錯(cuò)誤信息 error: bundling failed: NotFoundError: Cannot find entry file index.android.js in any of the roots 我們可以看出找不到入口文件index.android.js,而我們的入口文件是 index.js,因此我們需要另外加一些配置讓它知道我們的入口文件其實(shí)是 index.js
解決方法參考 react-native/issues/16517。在 app/ 目錄下的 build.gradle 文件中最上面添加
- apply plugin: 'com.android.application' // 這時(shí)原來(lái)存在的
- apply from: "../node_modules/react-native/react.gradle"
- project.ext.react = [
- entryFile: "index.js"
- ]
然后在 MainApplication 的 ReactNativeHost 類中添加:
- private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
- ...
- // 這是需要添加的
- @Override
- protected String getJSMainModuleName() {
- return "index";
- }
- }
重新在模擬器中運(yùn)行,就可以正常跳轉(zhuǎn)到 react-native 的頁(yè)面了。
【本文為51CTO專欄作者“林鑫”的原創(chuàng)稿件,轉(zhuǎn)載請(qǐng)通過(guò)微信公眾號(hào)聯(lián)系作者獲取授權(quán)】