参考
嵌入到现有原生应用
史上最详细的Android原生APP中添加ReactNative 进行混合开发教程
配置步骤
创建android项目
- 打开Android studio,Start a new Android Studio project 新建项目
- 其中 Application name: ReactNativeAppDemo,Company Domain: example.com,Minimum SDK: API 16:Android 4.1(Jelly Bean)
- 添加Empty Activity,其中 Activity Name: MainActivity,Layout Name: activity_main
- 在Android视图下,右键com.example.reactnativeappdemo,New -> Java Class,其中 Name:MyReactActivity
MainActivity.java完整代码如下:
MyReactActivity完整代码如下:
React Native集成到android项目中
- cmd进入在ReactNativeAPPDemo的根目录,执行 npm init
- 执行 npm install –save react react-native
- 执行 curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig,作用是下载.flowconfig配置文件,用于约束js代码的写法,也可以手动创建文件在浏览器打开这个网址复制内容,这一步非必需
package.json文件如下,注意react和react native的版本
12345678910111213141516{"name": "reactnativeappdemo","version": "1.0.0","description": "","main": "index.android.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","start": "node node_modules/react-native/local-cli/cli.js start"},"author": "","license": "ISC","dependencies": {"react": "~15.4.1","react-native": "0.42.0"}}添加index.android.js文件到项目中
12345678910111213141516171819202122232425262728import 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}>React Native:Hello, World</Text></View>);}}var styles = StyleSheet.create({container: {flex: 1,justifyContent: 'center',},hello: {fontSize: 20,textAlign: 'center',margin: 10,},});AppRegistry.registerComponent('HelloWorld', () => HelloWorld);app/build.gradle配置
1234dependencies {...compile "com.facebook.react:react-native:+" // From node_modules.}整个工程build.gradle配置
12345678910allprojects {repositories {...maven {// All of React Native (JS, Android binaries) is installed from npmurl "$rootDir/node_modules/react-native/android"}}...}app/src/main/AndroidManifest.xml配置
1234567891011121314...<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/><application...<activityandroid:name=".MyReactActivity"android:label="@string/app_name"android:theme="@style/Theme.AppCompat.Light.NoActionBar"></activity><activityandroid:name="com.facebook.react.devsupport.DevSettingsActivity"></activity></application>
启动项目
- 先运行android项目
- cmd进入在ReactNativeAPPDemo的根目录,执行 npm start
可能出现的错误
如果点击按钮后应用崩溃了,同时Android Studio中报错 permission denied for this window type ,需要开启悬浮窗(overlay)权限。
解决方法一,修改MainActivity.java中代码如下:
解决方法二,修改MyReactActivity.java中代码如下: