在已有的项目中引入react native

如果新建一个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撞车了,慢慢解决吧!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值