React native之路(七)集成ReactNative到已有項目(Android)

本來這一篇準備學習ReactNative的常用組件的比如button,listview這些,可是突然發(fā)現(xiàn)學習到現(xiàn)在所有的項目都是純ReactNative項目,還不知道怎樣融合到已有的原生項目中,而現(xiàn)在絕大部分的ReactNative應用均是采用融合到已有項目中的方式,把項目中的某一個模塊使用ReactNative來開發(fā),所以有必要弄清楚ReactNative是如何融合到已有項目的。查看了一下官方文檔,官方已經(jīng)告訴了我們?nèi)诤系?a target="_blank" rel="nofollow">詳細步驟,想著按照官網(wǎng)步驟一步一步來應該問題不大,結(jié)果還是天真了,真的是一步一個坑啊,官網(wǎng)你這個大騙子!周末就這樣沒了。所以這篇會詳細記錄一下融合過程中的各種坑,也給看到的小伙伴提個醒吧。開始之前確保你的PC中已經(jīng)正確安裝了node.js以及Python 2 ,如果還沒有安裝好,看這篇文章React Native之路(一)Windows下安裝配置,下面將結(jié)合官網(wǎng)的步驟開始踩坑之路:

1 新建一個Android項目


注意Minimum SDk選擇API16以上



一路next后finish。

2添加JS

打開studio的Terminal窗口,輸入如下命令:

npm init

會讓你輸入一些初始化package.json 的配置信息,例如



按照提示輸入就行了。
這一步完成之后,在項目的根目錄下就會生成package.json這個文件,打開之后長這個樣子:



下一步輸入:

npm install --save react react-native

用來安裝React 和React Native。



大約一兩分鐘的樣子(如果卡到這里了,看看安裝時是不是忘了配置鏡像),完成之后你的根目錄下會多了一個node_modules的文件夾,里面存放了下載好的React 和React Native。



下一步繼續(xù)輸入如下命令

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

如果PC中還沒有安裝curl命令在這里下載,下載后記得配置好環(huán)境變量哦(也就是把bin目錄下的curl命令加入到系統(tǒng)環(huán)境變量里),然后最重要的是重啟一下studio,要不然還是無法使用curl命令。
重啟studio后輸入curl會出現(xiàn)


說明已經(jīng)安裝成功了。
繼續(xù)上面的步驟輸入:

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

用于下載.flowconfig文件。顯示如下說明下載成功



接下來把如下命令粘貼到package.json 文件下 scripts標簽中

"start": "node node_modules/react-native/local-cli/cli.js start"

粘貼后的package.json文件內(nèi)容如下:


下一步,在根目錄下創(chuàng)建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('HelloWorld', () => HelloWorld);

代碼很簡單,居中顯示一個HelloWorld。

3 項目配置

修改app的build.gradle文件添加如下內(nèi)容,并修改appcompat-v7版本為23.0.1(只能基于此版本構(gòu)建)

android{
    ....
    ndk {
     abiFilters "armeabi-v7a", "x86"
    }
}
packagingOptions {
   exclude "lib/arm64-v8a"
}

configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}

dependencies {
    ...
    compile "com.facebook.react:react-native:+" // From node_modules.
    compile 'com.android.support:appcompat-v7:23.0.1'
}

修改后的build.gradle完整內(nèi)容如下:

apply plugin: 'com.android.application'

android {
        compileSdkVersion 25
        buildToolsVersion "25.0.2"
        defaultConfig {
        applicationId "com.reactnative.example"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
    packagingOptions {
        exclude "lib/arm64-v8a"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.facebook.react:react-native:+'
    testCompile 'junit:junit:4.12'
}

項目的build.gradle中添加依賴

allprojects {
repositories {
    ...
    maven {
        // All of React Native (JS, Android binaries) is installed from npm
        url "$rootDir/../node_modules/react-native/android"
    }
}
...
}

編譯通過之后查看一下使用的react-native版本


居然是0.20.1,這和目前的最新版0.43.2差的太遠了,最新版在這里查看,或者項目中node_modules/react-native/android/
解決方案是把在項目build.gradle中配置的

url "$rootDir/../node_modules/react-native/android"

改成

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

重新編譯,發(fā)現(xiàn)已經(jīng)變成了0.43.2了。
繼續(xù)下一步,在AndroidManifest.xml中添加網(wǎng)絡訪問權(quán)限

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

3 創(chuàng)建Activity

以下幾步不要安裝官網(wǎng)的去做,官網(wǎng)的步驟太麻煩,而且很久沒有更新了。

1新建一個Activity,讓其繼承ReactActivity,并重寫getMainComponentName(),返回我們在index.android.js
中注冊的HelloWorld這個組件。



2自定義一個Application,繼承ReactApplication ,編寫以下代碼:

public class App 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;
    }
}

記得在AndroidManifest.xml中引用

android:name=".App"

在MainActivity中通過按鈕啟動我們的ReactNativeActivity

findViewById(R.id.start_rn_btn).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, ReactNativeActivity.class));
        }
});

下一步,app/src/main下新建assets文件夾。
運行如下命令

react-native start

如果卡在了這一步:



沒關(guān)系,用資源管理器打開你工程的根目錄,在此目錄下重新運行一個命令行并在其中輸入如下命令

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/


完成之后assets目錄下會生成以下兩個文件



確認一下react native service處于運行狀態(tài),然后正常運行你的APP,點擊start,如果出現(xiàn)



恭喜你!你已經(jīng)可以開始搞混合開發(fā)了。
下一篇開始各種組件學習,歡迎大家關(guān)注,共同進步!
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容