不僅可以在react native 的js界面和現有工程的界面之間跳轉,而且可以把js寫的界面當成一個控件,嵌入到現有的activity,作爲原生界面的一部分使用。
第一節:按照官方的例子,把js寫頁面放在一個activity,在原生應用裏啓動該activity。
第二步:進入你工程的根目錄,在命令行運行下面的命令:
$ npm init
這個命令會創建package.json文件,輸入這個命令後,會提示你輸入一系列參數。按照提示輸入:我輸入的
參數如下:
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (myAppWithTest) integrate // 輸入項目名稱
version: (1.0.0) // 回車,使用默認版本號
description: test native for react // 輸入項目描述
entry point: (index.js) // 回車,使用默認文件名
test command: // 回車,使用默認值
git repository: // 回車留空或填入Git地址
keywords: react test // 填寫關鍵字react和test
author: andy // 填寫作者
license: (ISC) // 回車,使用默認值
上面填完後,再輸入下面的命令:
$ npm install --save react react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
上面的命令執行後,會創建node_modules目錄。
第三步:打開在根目錄下剛纔創建好的package.json文件,添加下面一行
"start": "node node_modules/react-native/local-cli/cli.js start"
第四步:編輯index.android.js文件,加入簡單的代碼,你可以copy下面的代碼到該文件:
'use strict';
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class HelloWorld extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.hello}>Hello, Andy</Text>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
hello: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
第五步:在你app的build.gradle文件中添加react native依賴庫
compile "com.facebook.react:react-native:+" // From node_modules
第六步:在你project的 build.gradle文件中添加 react native路徑:
allprojects {
repositories {
...
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/node_modules/react-native/android"
}
}
...
}
第七步:在你的AndroidManifest.xml文件中添加網絡權限
<uses-permission android:name="android.permission.INTERNET" />
第八步:創建一個加載JS代碼的activity,activity的代碼如下:
public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
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, "HelloWorld", null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
}
第九步:在AndroidManifest.xml文件中,爲剛纔創建的activity指定一個主題,
<activity
android:name=".MyReactActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
第十步:添加一些activity的生命週期函數,並添加一些代碼:
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy();
}
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
第十一步:在MyReactActivity中添加按鍵響應函數:
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
第十二步:在hello world程序的界面上添加一個按鈕,加載MyReactActivity。
Button bt = (Button)findViewById(R.id.start_react); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this,MyReactActivity.class); startActivity(intent); } });
第十三步:到這裏基本可以在android studio中運行程序了,先在命令行啓動js所需的服務器,執行下面的命令即可:
$ npm start
最後,在android studio,像啓動其他程序一樣運行程序,點擊按鈕就可以加載react native界面了。激動吧。如下圖:
第二節:將react native 寫的界面當成組建嵌入到現有的activity。
這個其實比較簡單,新建一個佈局xml文件,在上面的創建的MyReactActivity的onCreate函數中,像原生一樣調用setContentView(R.layout.native_js); 然後通過addView 把reactnative 的界面,加入進入。下面是完整的onCreate函數代碼:
public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.native_js);
mReactRootView = new ReactRootView(this);
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, "HelloWorld", null);
LinearLayout view = (LinearLayout) findViewById(R.id.react_root);
view.addView(mReactRootView);
}
編譯運行,如下圖,灰色是原聲界面部分,藍色爲react native界面:
問題:今天【20160908】將react native嵌入到原生應用後,運行碰到下面的錯誤。
解決辦法:我另外用命令react-native init test.新建了一個應用,然後把新工程node_modules目錄下的react目錄copy到了對應的位置。