已有Android工程集成ReactNative页面
React Native出自Facebook之手, 而且刚刚更新了文档, 差一点我就放弃它了, 然而又捞了回来, 相比其他, 毕竟还是大公司大品牌有保障. 不多说了, 想知道更多, 自己网上看吧.
网址: http://facebook.github.io/react-native/
让我们看看Docs中Android的Guides.
Integrating with Existing Apps
里面是教如何在已有的Android项目集成ReactNative. 文档有一些问题, 容我慢慢说来.
1. JS框架
新建HelloWorld是必备的.
配置命令行环境参考: http://facebook.github.io/react-native/docs/getting-started.html#content (Getting Started)
设置node_modules, 就是配置JS文档所说的, 在项目中, 调用npm install --save react-native
, 然速度特别特别慢, 几乎是不可能完成的任务(我是没有完成). 然而这个react-native应该是通用的, 下载复制一份就好, 放在根目录.
使用react-native init AwesomeProject
生成测试项目, 把AwesomeProject项目的node_modules复制出来即可.
更换服务器, 也可以提高下载速度.
$ npm install -g cnpm --registry=http://registry.npm.taobao.org
同样也需要复制的是package.json, 也可以使用npm init
配置, 不过比较麻烦, 要添好多参数.
package.json的内容
{
"name": "AwesomeProject",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node_modules/react-native/packager/packager.sh"
},
"dependencies": {
"react-native": "^0.12.0"
}
}
然后再调用最后一个命令
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
创建HTML5的主页面index.android.js
, 按着文档编辑即可.
这里提供一份新的代码
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
Image,
StyleSheet,
Text,
View,
ListView,
} = React;
var MOCKED_MOVIES_DATA = [
{title: 'Title', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}},
];
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
var AwesomeProject = React.createClass({
componentDidMount: function() {
this.fetchData();
},
getInitialState: function() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
},
fetchData: function() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true,
});
})
.done();
},
render: function() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
);
},
renderLoadingView: function() {
return (
<View style={styles.container}>
<Text>
Loading movies...
</Text>
</View>
);
},
renderMovie: function(movie) {
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
thumbnail: {
width: 53,
height: 81,
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
这里需要修改MainActivity的Application名称, MyAwesomeApp
->AwesomeProject
.
mReactRootView.startReactApplication(mReactInstanceManager, "AwesomeProject", null);
这样就完成了react-native的JS框架配置.
2. 添加代码
下面开始代码的添加, 设置build.gradle
, 集成react-native的maven库.
compile 'com.facebook.react:react-native:0.13.0'
添加权限
<uses-permission android:name="android.permission.INTERNET" />
添加网络设置Activity
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
我的代码和Demo略有不同, 本质上都是在ReactRootView内添加H5的页面.
资源文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
...
>
<TextView
android:id="@+id/test_text"
.../>
<com.facebook.react.ReactRootView
android:id="@+id/test_js"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/test_text"/>
</RelativeLayout>
源文件, 主要是设置ReactRootView.
public class MainActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mReactRootView = (ReactRootView) findViewById(R.id.test_js);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "MyAwesomeApp", null);
// setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onResume(this);
}
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
}
基本的代码部分已经配置完成.
3. 真机调试
最后是启动配置, 针对Android的真机调试.
在build.gradle中, 添加ndk支持.
defaultConfig {
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
在gradle.properties中, 添加ndk选项.
android.useDeprecatedNdk=true
设置ndk的目的是设置Debug Server Host, 设置IP.
进入项目根目录启动服务npm start
然后启动App程序, 初始时是红色错误页面, 晃动手机, 选择
Dev Settings
, 选择最后的Debug server host for device
, 把当前网络IP写入其中即可.
设置IP
然后再Reload JS
OK, enjoy it.