ReactNative推出也有一段日子了,相信很多開發者都想體驗一下rn的強大功能,但是目前代碼都是基于native代碼的,如何加入ReactNative的代碼呢?本文將從簡單介紹下如何在已有工程的基礎上,新增ReactNative模塊。
準備條件
1.一個已有的、基于gradle構建的Android應用。
2.Node.js,參見開始使用React Native來了解相關的設置操作。
首先創建個Android工程,結構如下圖所示:
下面我們開始在這個原生android工程上進行改造,加入我們的ReactNative代碼。
在android/app/build.gradle文件中,添加React Native依賴:
// From node_modules
compile"com.facebook.react:react-native:+"
然后在android/build.gradle文件中(注意跟上面的路徑不同)加入本地React Native的maven目錄(現在React Native的所有組件,無論JS還是Android的預編譯包,都是通過npm分發的了):
allprojects {
repositories {
...
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/node_modules/react-native/android"
}
}
...
}
最后在你的AndroidManifest.xml里增加Internet訪問權限:
<uses-permission android:name="android.permission.INTERNET" />
添加原生代碼
你需要添加一些原生代碼來啟動React Native運行庫以及讓它渲染出東西來。我們接下來創建一個Activity和一ReactRootView
,然后在里面啟動一個React應用并把它設置為Activity的主要內容視圖。
public class MainActivity extends AppCompatActivity 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, "HelloRn", null);
setContentView(mReactRootView);
}}
接下來,我們需要傳遞一些Activity的生命周期事件到ReactInstanceManager
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
我們還需要把Back按鈕事件傳遞給React native:
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
把JS代碼添加到你的應用
在你的工程根目錄,運行以下代碼:
$ npm init
$ npm install --save react
$ npm install --save react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
上面的代碼會創建一個node模塊,然后react-native作為npm依賴添加。現在打開新創建的package.json文件然后在scripts字段下添加如下內容:
"start": "node node_modules/react-native/local-cli/cli.js start"
復制并粘貼下面的這段代碼到你工程根目錄下的index.android.js
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Text,
StyleSheet,
View,
} from 'react-native';
class HelloRn extends 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('HelloRn', () => HelloRn);
運行應用
為了運行應用,首先要啟動開發服務器。只需要在你的工程目錄下運行這段代碼:
$ npm start
現在來構建和運行你的Android應用(譬如./gradlew installDebug
)。一旦啟動了React Native制作的Activity,它應該會從開發服務器加載代碼并顯示:
可能遇到的問題:
-
Manifest merger failed : uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library [com.facebook.react:react-native:0.29.2]
在mainfest配置如下參數即可:
-
java.lang.UnsatisfiedLinkError: could find DSO to load: libreactnativejni.so
在兩處添加配置:
app#build.gradledefaultConfig { //... ndk { abiFilters "armeabi-v7a", "x86" } }
gradle.properties
android.useDeprecatedNdk=true
3.報錯信息如下:
Loading dependency graph, done.
error: bundling: UnableToResolveError: Unable to resolve module `react/lib/ReactDebugCurrentFrame` from `/Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react-native/Libraries/Renderer/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js`: Module does not exist in the module map or in these directories:
/Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react-native/node_modules/react/lib
, /Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react/lib
, /Users/suwantao/node_modules/react/lib
This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
1. Clear watchman watches: `watchman watch-del-all`.
2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
3. Reset packager cache: `rm -fr $TMPDIR/react-*` or `npm start --reset-cache`.
at UnableToResolveError (/Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react-native/packager/src/node-haste/DependencyGraph/ResolutionRequest.js:488:5)
at p.catch.error (/Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react-native/packager/src/node-haste/DependencyGraph/ResolutionRequest.js:366:19)
at process._tickCallback (internal/process/next_tick.js:103:7)
Bundling `index.android.js` 84.3% (349/380), failed.
解決方案:添加 react-native-material-design
react-native-material-design依賴react-native-material-design-styles ,如果他的父類是個全局的模塊,則不能被React Native's bundler打包。
參考The development server returned response error code: 500 in react native
執行npm install react-native-material-design 如果報錯,
根據提示,執行:npm install --save react@16.0.0-alpha.6
安裝成功之后再次執行npm install react-native-material-design即可。
4.詭異的問題
解決方案:
app/build.gradle (將 'com.android.support:appcompat-v7:xx.x.x' 改為 'com.android.support:appcompat-v7:23.0.1')
5.undefined is not an object (evaluating ‘ReactInternals.ReactCurrentOwner’)
解決方案:
參考:https://github.com/facebook/react-native/issues/13874
由于本地沒安裝yarm,無法直接調用 yarn add react@16.0.0-alpha.12在package.json手動填入"react": "16.0.0-alpha.12"也沒解決問題。
最后通過一個熱心網友解決了該問題。方案如下:
在項目根目錄輸入 npm install 然后 npm start ,問題完美解決。