如果新建一个react native
项目,在Android
中写native
的话是很容易的,一般情况下项目已经存在,如何在已经存在的app中引入react native
呢?
Prepare your app
首先在你的app中的build.gradle
引入react native
的jar包
- compile "com.facebook.react:react-native:+"
在项目的build.gradle
中加入本地react native
的maven地址
- repositories {
- jcenter()
- maven {
- // All of React Native (JS,Android binaries) is installed from npm
- url "$projectDir/../../node_modules/react-native/android"
- }
- }
然后在app中的AndroidManifest.xml
中添加网络权限,一般都存在了,这一部可以忽略
- <uses-permission android:name="android.permission.INTERNET" />
Add native code
添加本地代码确保react native
启动,开始渲染,当开启一个Activity
时创建一个ReactRootView
,启动react
并且把它作为主控件
- public class RNTestActivity extends ReactActivity {
-
-
- @Override
- protected String getMainComponentName() {
- return "MyAwesomeApp";
- }
-
- @Override
- protected boolean getUseDeveloperSupport() {
- return BuildConfig.DEBUG;
- }
-
- @Override
- protected List<ReactPackage> getPackages() {
- return Arrays.<ReactPackage>asList(
- new MainReactPackage()
- );
- }
- }
Add JS to your app
在项目根文件执行一下命令:
- $ npm init
- $ npm install --save react-native
- $ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
创建了node_modules
文件,添加了react-native
依赖包,现在打开新建的package.json
文件,在scripts
标签中加入
- "start": "node node_modules/react-native/local-cli/cli.js start"
然后在index.android.js中写入相关代码
- import React from 'react';
- import {
- AppRegistry,StyleSheet,Text,View
- } from 'react-native';
-
- class MyAwesomeApp 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('MyAwesomeApp',() => MyAwesomeApp);
吐槽:react native
都到0.29了,结果在导入原生项目中只到0.20.1,还各种落后的jar包,还有就是各种版本配置的包也是奇葩,不兼容最新的,个人感觉很垃圾,不过还好,毕竟没有到1.0,1.0要是再出现这么恶心的问题,就只能呵呵了
如果你遇到了Method 'void android.support.v4.net.ConnectivityManagerCompat.()' is inaccessible to class 'com.facebook.react.modules.netinfo.NetInfoModule'
这个问题那么恭喜你,不兼容com.android.support:appcompat-v7:23.2.1
将 com.android.support:appcompat-v7:23.2.1
改为 com.android.support:appcompat-v7:23.0.1
如果你遇到了更多的奇葩问题,那就是react native
与app撞车了,慢慢解决吧!