没事做个记录, 也算是温故而知新吧.
背景: 现已有一个名为demo1031
的安卓原生项目, 要添加react-native进来实现一部分功能.
效果如下, 第一个页面是原生页面, 第二个页面是react-native页面.
步骤:
在
app\build.gradle
的dependencies
标签下添加:compile "com.facebook.react:react-native:+"
;在
app\build.gradle
的android
标签下添加:configurations.all { resolutionStrategy.force 'com.google.code.findbugs:jsr305:+' }
在
app\build.gradle
的android\defaultConfig
标签下添加:ndk { abiFilters "armeabi-v7a", "x86" }
在
build.gradle
的allprojects\repositories
标签下添加:maven { url "$rootDir/reactnative/node_modules/react-native/android" }
在
gradle.properties
内添加:android.useDeprecatedNdk=true
-
创建一个activity文件
RNActivity
:public class RNActivity extends ReactActivity { @Nullable @Override protected String getMainComponentName() { return "demo1031"; } }
-
创建一个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
内指定application
路径android:name=".RNApplication"
-
在项目目录下创建
reactnative
文件夹, 在reactnative
文件夹创建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
文件夹创建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);
在项目目录文件夹reactnative下执行命令
npm i
, 然后再npm start
使用Android studio运行项目, ok, 收工!
假如报错: Unable to load script from assets 'index.android.bundle'...
, 可以在项目main文件夹下新建文件夹assets
, 然后在reactnative下运行命令: 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/