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

5次阅读

共计 1672 个字符,预计需要花费 5 分钟才能阅读完成。

在已有 app 混合开发时,可能会有多个 rn 界面入口的需求,这个时候我们可以使用 RCTRootView 中的 moduleNameinitialProperties来实现加载包中的不同页面。

目前使用 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 这样的导航组件搭配使用,下面贴出的代码就是结合路由的实现方案。

screenPropsreact-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