我正在开发一个现有的大型Android和iOs项目,我的团队希望采用本机反应。首先,我们希望在RN中实现一个功能,因为我们没有能力一次性迁移整个项目。
我成功地从本地节点服务器和位于assets文件夹中的JS捆绑文件中成功添加了RN视图,但感觉有点笨拙。我知道iO支持这一点但我在文档中找不到与现有Android项目集成的任何内容。以下是我提出的要点:
public class ReactNativeView extends FrameLayout {
private static final String COMPONENT_NAME = "AwesomeProject";
// Path of our RN module relative to project root
private static final String MODULE_NAME = "react-sources/index.android"
public ReactNativeView(Context Context) {
super(context);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
ReactInstanceManager.Builder builder = ReactInstanceManager.builder()
.setApplication(AppDelegate.sharedApplication())
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.BEFORE_RESUME);
if (BuildConfig.USE_RN_LOCAL_SERVER) {
// Set module name to be loaded from local node server
builder.setJSMainModuleName(MODULE_NAME);
} else {
Uri uri = AssetsManager.getInstance().getJsBundleUri();
// Load bundled jsBundle
builder.setJSBundleFile(uri.getPath());
}
ReactInstanceManager reactInstanceManager = builder.build();
MainActivity mainActivity = MainActivity.getMainActivity();
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
ReactRootView reactRootView =
new ReactRootView(AppDelegate.sharedApplication().getTopActivity());
// Is it really necessary to call 'startReactApplication' each time we want to render a react component?
reactRootView.startReactApplication(reactInstanceManager, COMPONENT_NAME, null);
addView(reactRootView);
// After the view is added to the hierarchy we call the manager's 'onResume' function
// to show the react view
reactInstanceManager.onResume(mainActivity, mainActivity); // <-- What kind of sorcery is this?!
}
}
我还在BuildConfig中添加了一个变量来确定要使用哪个JS包:
buildTypes {
debug {
buildConfigField "boolean", "USE_RN_LOCAL_SERVER", "true" // load from local server
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "boolean", "USE_RN_LOCAL_SERVER", "false"
}
}
这是一个完整的黑客攻击。当我正在做的事情只是在屏幕上添加视图时,调用startReactApplication
感觉很尴尬。我错过了API或者这不是支持的方案吗?
答案 0 :(得分:0)
您是否检查了RN official doc有关此主题的信息?
它向您展示了如何在Java编码的Android应用程序中干净地运行RN视图。
答案 1 :(得分:0)
显然,调用startReactApplication
确实是要纠正的方法。如果有人对更完整,更有条理的解决方案感兴趣,您可以查看react-native-navigation。