
本文的合集已經(jīng)編著成書,高級Android開發(fā)強化實戰(zhàn),歡迎各位讀友的建議和指導。在京東即可購買:https://item.jd.com/12385680.html

React Native出自Facebook之手, 而且剛剛更新了文檔, 差一點我就放棄它了, 然而又撈了回來, 相比其他, 畢竟還是大公司大品牌有保障. 不多說了, 想知道更多, 自己網(wǎng)上看吧.
網(wǎng)址: http://facebook.github.io/react-native/
讓我們看看Docs中Android的Guides.
Integrating with Existing Apps
里面是教如何在已有的Android項目集成ReactNative. 文檔有一些問題, 容我慢慢說來.
1. JS框架
新建HelloWorld是必備的.
配置命令行環(huán)境參考: http://facebook.github.io/react-native/docs/getting-started.html#content (Getting Started)
設置node_modules, 就是配置JS文檔所說的, 在項目中, 調(diào)用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配置, 不過比較麻煩, 要添好多參數(shù).
package.json的內(nèi)容
{
"name": "AwesomeProject",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node_modules/react-native/packager/packager.sh"
},
"dependencies": {
"react-native": "^0.12.0"
}
}
然后再調(diào)用最后一個命令
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
創(chuàng)建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'
添加權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
添加網(wǎng)絡設置Activity
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
我的代碼和Demo略有不同, 本質(zhì)上都是在ReactRootView內(nèi)添加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);
}
}
基本的代碼部分已經(jīng)配置完成.
3. 真機調(diào)試
最后是啟動配置, 針對Android的真機調(diào)試.
在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, 把當前網(wǎng)絡IP寫入其中即可.

然后再Reload JS

OK, enjoy it.