您的位置:首页 > Web前端 > React

在已有的项目中引入react native

2016-07-05 14:32 651 查看
如果新建一个
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[/code] 
创建了
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撞车了,慢慢解决吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  react native