讲解ReactActivity之前,需要理清如下三个类之间的关系:
1.ReactActivity;
2.ReactActivityDelegate;
3.ReactDelegate;
通过源码我们看到,ReactAcitivy -> ReactActivityDelegate -> ReactDelegate,三者之间是包含与被包含关系;
ReactActivity相关的行为都由ReactActivityDelegate代理,其中有两个方法需要注意:
protected final void loadApp(String appKey) {
mDelegate.loadApp(appKey);
}
该方法提供整个module加载的入口,RN框架如果经过修改,它本身是支持加载多bundle。
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component. e.g. "MoviesApp"
*/
protected @Nullable String getMainComponentName() {
return null;
}
上面方法注释已经解释很清楚,它提供了main component的名称,告诉框架,该Activity对应的ReactRootView最终会加载哪个component。
接下来继续看ReactActivityDelegate类,该类部分功能由ReactDelegate代理,我们先看如下方法:
protected void onCreate(Bundle savedInstanceState) {
String mainComponentName = getMainComponentName();
mReactDelegate =
new ReactDelegate(
getPlainActivity(), getReactNativeHost(), mainComponentName, getLaunchOptions()) {
@Override
protected ReactRootView createRootView() {
return ReactActivityDelegate.this.createRootView();
}
};
if (mMainComponentName != null) {
loadApp(mainComponentName);
}
}
我们看到,当activity创建完,会执行onCreate方法,该方法核心逻辑如下:
1.创建ReactDelegate;
2.执行loadApp方法,加载component;
先来看ReactDelegate类的实现,该类一部分功能由外部传进来的ReactNativeHost代理,提供ReactInstanceManager类,同时会提供创建ReactRootView方法。
再来看loadApp,具体到ReactDelegate里的loadApp,代码如下:
public void loadApp(String appKey) {
if (mReactRootView != null) {
throw new IllegalStateException("Cannot loadApp while app is already running.");
}
mReactRootView = createRootView();
mReactRootView.startReactApplication(
getReactNativeHost().getReactInstanceManager(