React Native 混合开发多入口加载方式详解

在已有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);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面