在已有的項目中引入react native

如果新建一個react native項目,在Android中寫native的話是很容易的,一般情況下項目已經(jīng)存在,如何在已經(jīng)存在的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中添加網(wǎng)絡(luò)權(quán)限,一般都存在了,這一部可以忽略

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

Add native code

添加本地代碼確保react native啟動,開始渲染,當(dāng)開啟一個Activity時創(chuàng)建一個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

在項目根文件執(zhí)行一下命令:

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

創(chuàng)建了node_modules文件,添加了react-native依賴包,現(xiàn)在打開新建的package.json文件,在scripts標(biāo)簽中加入

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

然后在index.android.js中寫入相關(guān)代碼


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了,結(jié)果在導(dǎo)入原生項目中只到0.20.1,還各種落后的jar包,還有就是各種版本配置的包也是奇葩,不兼容最新的,個人感覺很垃圾,不過還好,畢竟沒有到1.0,1.0要是再出現(xiàn)這么惡心的問題,就只能呵呵了

如果你遇到了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撞車了,慢慢解決吧!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容