在已有app混合开发时,可能会有多个rn界面入口的需求,这个时候我们可以使用RCTRootView中的moduleName或initialProperties来实现加载包中的不同页面。
目前使用RCTRootView有两种方式:
- 使用
initialProperties传入props属性,在React中读取属性,通过逻辑来渲染不同的Component - 配置
moduleName,然后AppRegistry.registerComponent注册同名的页面入口
这里贴出使用0.60.5版本中ios项目的代码片段:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:@"AwesomeProject"
initialProperties: @{
@"screenProps" : @{
@"initialRouteName" : @"Home",
},
}];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;
}
initialProperties
这种方式简单使用可以通过state判断切换界面,不过项目使用中还是需要react-navigation这样的导航组件搭配使用,下面贴出的代码就是结合路由的实现方案。
screenProps是react-navigation中专门用于传递给React组件数据的属性,createAppContainer创建的组件接受该参数screenProps,并传给访问的路由页面。
class App extends React.Component {
render() {
const { screenProps } = this.props;
const stack = createStackNavigator({
Home: {
screen: HomeScreen,
},
Chat: {
screen: ChatScreen,
},
}, {
initialRouteName: screenProps.initialRouteName || 'Home',
});
const AppContainer = createAppContainer(stack);
return (
<AppContainer
screenProps
/>
);
}
}
moduleName
我们按照下面代码注册多个页面入口之后,就可以在原生代码中指定moduleName等于AwesomeProject或者AwesomeProject2来加载不同页面。
AppRegistry.registerComponent("AwesomeProject", () => App);
AppRegistry.registerComponent("AwesomeProject2", () => App2);
版权声明:本文为原创文章,版权归 neo 所有。
本文链接:https://idayer.com/react-native-load-multi-entry-bundle/
本作品采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可。

请教个问题,如果我想打包时候可以只包含一份代码,而不是所有应该怎么处理,
例如命令行1只打包入口a
命令行2只打包入口b
你这个可能算是拆包的需求了,可以看下react-native-multibundler。另外简单点的话,你可以命令里添加自定义的环境变量,在入口里判断注册。