沒事做個(gè)記錄, 也算是溫故而知新吧.
背景: 現(xiàn)已有一個(gè)名為demo1031
的安卓原生項(xiàng)目, 要添加react-native進(jìn)來實(shí)現(xiàn)一部分功能.
效果如下, 第一個(gè)頁面是原生頁面, 第二個(gè)頁面是react-native頁面.
步驟:
在
app\build.gradle
的dependencies
標(biāo)簽下添加:compile "com.facebook.react:react-native:+"
;在
app\build.gradle
的android
標(biāo)簽下添加:configurations.all { resolutionStrategy.force 'com.google.code.findbugs:jsr305:+' }
在
app\build.gradle
的android\defaultConfig
標(biāo)簽下添加:ndk { abiFilters "armeabi-v7a", "x86" }
在
build.gradle
的allprojects\repositories
標(biāo)簽下添加:maven { url "$rootDir/reactnative/node_modules/react-native/android" }
在
gradle.properties
內(nèi)添加:android.useDeprecatedNdk=true
-
創(chuàng)建一個(gè)activity文件
RNActivity
:public class RNActivity extends ReactActivity { @Nullable @Override protected String getMainComponentName() { return "demo1031"; } }
-
創(chuàng)建一個(gè)Application文件
RNApplication
: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,false); } }
在
AndroidManifest.xml
內(nèi)指定application
路徑android:name=".RNApplication"
-
在項(xiàng)目目錄下創(chuàng)建
reactnative
文件夾, 在reactnative
文件夾創(chuàng)建package.json
文件:{ "name": "reactnative", "version": "0.0.1", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "jest" }, "dependencies": { "react": "16.0.0-beta.5", "react-native": "0.49.5" }, "devDependencies": { "babel-jest": "21.2.0", "babel-preset-react-native": "4.0.0", "jest": "21.2.1", "react-test-renderer": "16.0.0-beta.5" }, "jest": { "preset": "react-native" } }
-
在
reactnative
文件夾創(chuàng)建index.android.js
文件:import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Button } from 'react-native'; export default class Index extends Component { _onPress() { alert("我是react-native彈窗"); } render() { return ( <View style={styles.container}> <Button title="Button" color="#ff8500" onPress={()=> this._onPress()}/> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, }); AppRegistry.registerComponent('reactnative', () => Index);
在項(xiàng)目目錄文件夾reactnative下執(zhí)行命令
npm i
, 然后再npm start
使用Android studio運(yùn)行項(xiàng)目, ok, 收工!
假如報(bào)錯(cuò): Unable to load script from assets 'index.android.bundle'...
, 可以在項(xiàng)目main文件夾下新建文件夾assets
, 然后在reactnative下運(yù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/