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

以上就是【React Native 混合开发多入口加载方式详解】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)
发表我的评论

最新评论

  1. 暂无评论