注意:本教程預設已經安裝所有的配置,例如react-native、node.js等
第一步、建立React Native工程目錄
先建立一個檔案夾,命名為HelloWorld
第二步、建立android工程
通過android studio在HelloWorld檔案夾下面建立android工程,工程名命名為android。
第三步、配置android工程
1、在項目的build.gradle檔案中添加依賴,我的react native的版本。大家可以根據自己的版本進行依賴添加:具體如下:
2、在AndroidManifest.xml檔案中加入網絡權限
3、在AndroidManifest.xml中注冊debug模式下的調試Activity
4、修改MainActivity
public class MainActivity 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, "showHelloWorld", 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,this);
}
}
}
其中有一句代碼如下:
mReactRootView.startReactApplication(mReactInstanceManager, "showHelloWorld", null);
此代碼中的“showHelloWorld”後面要用到
第四步、其他配置
1、啟動終端,進入到HelloWorld檔案下,運作指令npm init,此時需要使用者輸入一些資訊,其中隻有name是必須的,使用者輸入name,其他 資訊直接預設就可以。執行完這一步,使用者可以在HelloWolrd檔案夾下看到pageage.json檔案,打開就可以看到剛才輸入的配置資訊。
2、運作指令npm install –save react-native,安裝react native子產品以及相關node子產品。結束後會在HelloWorld檔案夾中看到node_modules檔案夾。PS:此過程時間有一些長,網絡不好,還有可能有的依賴下載下傳不下來,我就因為這個踩了坑。運作的時候缺少依賴。又重新npm install的。
3、配置flow,運作指令如下:
4、修改之前生成的package.json檔案,在scripts标簽中添加如下代碼
删除原來的
5、建立js檔案、命名為index.android.js,添加如下代碼:
'use strict';
var React = require('react-native');
var {
Text,
View
} = React;
class MyAwesomeApp extends React.Component {
render() {
return (
<view style={styles.container}>
<text style={styles.hello}>Hello, World</text>
</view>
)
}
}
var styles = React.StyleSheet.create({
container: {
flex: ,
justifyContent: 'center',
},
hello: {
fontSize: ,
textAlign: 'center',
margin: ,
},
});
React.AppRegistry.registerComponent('showHelloWorld', () => MyAwesomeApp);
還記得上文提到的那個showHelloWorld嗎?在這裡用到了,這兩個要對應起來。并且此js檔案中的
class MyAwesomeApp extends React.Component {
這行代碼中的MyAwesomeApp要和
React.AppRegistry.registerComponent('showHelloWorld', () => MyAwesomeApp)
這行代碼中的MyAwesomeApp對應起來!
6、啟動npm:運作指令npm start等npm啟動,注意其中的端口号,一般是8081
7、運作android:在HelloWorld目錄下,運作指令react-native run-android,啟動app!
注意:1、如果是在真機測試,需要開啟彈窗的權限
2、真機測試,需要連接配接伺服器,app啟動後,搖一搖,打開debugActivity,點選最後行,輸入你電腦的ip和端口号,就是剛才提到的端口号,一般是8081
到此結束!
第一次寫部落格,歡迎指出錯誤的地方!
參考:http://www.lcode.org/【react-native開發】react-native移植原生android項目/