在已有的项目中引入react native

前端之家收集整理的这篇文章主要介绍了在已有的项目中引入react native前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

如果新建一个react native项目,在Android中写native的话是很容易的,一般情况下项目已经存在,如何在已经存在的app中引入react native呢?

Prepare your app

首先在你的app中的build.gradle引入react native的jar包

  1. compile "com.facebook.react:react-native:+"

在项目的build.gradle中加入本地react native的maven地址

  1. repositories {
  2. jcenter()
  3. maven {
  4. // All of React Native (JS,Android binaries) is installed from npm
  5. url "$projectDir/../../node_modules/react-native/android"
  6. }
  7. }

然后在app中的AndroidManifest.xml添加网络权限,一般都存在了,这一部可以忽略

  1. <uses-permission android:name="android.permission.INTERNET" />

Add native code

添加本地代码确保react native启动,开始渲染,当开启一个Activity时创建一个ReactRootView,启动react并且把它作为主控件

  1. public class RNTestActivity extends ReactActivity {
  2.  
  3.  
  4. @Override
  5. protected String getMainComponentName() {
  6. return "MyAwesomeApp";
  7. }
  8.  
  9. @Override
  10. protected boolean getUseDeveloperSupport() {
  11. return BuildConfig.DEBUG;
  12. }
  13.  
  14. @Override
  15. protected List<ReactPackage> getPackages() {
  16. return Arrays.<ReactPackage>asList(
  17. new MainReactPackage()
  18. );
  19. }
  20. }

Add JS to your app

在项目根文件执行一下命令:

  1. $ npm init
  2. $ npm install --save react-native
  3. $ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

创建了node_modules文件添加react-native依赖包,现在打开新建的package.json文件,在scripts标签中加入

  1. "start": "node node_modules/react-native/local-cli/cli.js start"

然后在index.android.js中写入相关代码

  1. import React from 'react';
  2. import {
  3. AppRegistry,StyleSheet,Text,View
  4. } from 'react-native';
  5.  
  6. class MyAwesomeApp extends React.Component {
  7. render() {
  8. return (
  9. <View style={styles.container}>
  10. <Text style={styles.hello}>Hello,World</Text>
  11. </View>
  12. )
  13. }
  14. }
  15. var styles = StyleSheet.create({
  16. container: {
  17. flex: 1,justifyContent: 'center',},hello: {
  18. fontSize: 20,textAlign: 'center',margin: 10,});
  19.  
  20. 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撞车了,慢慢解决吧!

猜你在找的React相关文章