1.首先集成的项目目录
我使用的是直接依照react-native init Project 的格式来导入的,也就是说,我的Android项目目录是跟node_modules是在1个目录下的。
我们init完项目以后,项目初始化完成了,这时候候我们可以用命令react-native run-android直接运行项目,至于怎样调试,之前已说过。
说1下我们怎样开发和运行分开吧,我们开发1般会选择webstrom,开发后我们会Android和ios的编译分开。
启动npm
下面说1下android 嵌入RN环境吧。
编写Android原生代码,用来调用RN
package com.reactdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
public class MainActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
@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, "ReactDemo", null);
setContentView(mReactRootView);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
}
注意要加上网络等1些权限。创建package.json,添加react native包
使用命令npm init,随着步骤走就行了,给大家截个图:
最后你就能够在你的RN项目里面看到1个package.json。
运行Demo
注:可能会出现java.lang.RuntimeException: Could not get BatchedBridge, make sure your bundle is packaged correctly这个毛病,
react-native bundle —platform android —dev false —entry-file index.android.js —bundle-output ReactDemo/app/src/main/assets/index.android.bundle —sourcemap-outpu ReactDemo/app/src/main/assets/index.android.map —assets-dest ReactDemo/app/src/main/res/