React Native 混合開發(fā)多入口加載方式詳解
在已有app混合開發(fā)時,可能會有多個rn界面入口的需求,這個時候我們可以使用RCTRootView中的moduleName或initialProperties來實現(xiàn)加載包中的不同頁面。
目前使用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這樣的導(dǎo)航組件搭配使用,下面貼出的代碼就是結(jié)合路由的實現(xiàn)方案。
screenProps是react-navigation中專門用于傳遞給React組件數(shù)據(jù)的屬性,createAppContainer創(chuàng)建的組件接受該參數(shù)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);
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
create-react-app中添加less支持的實現(xiàn)
這篇文章主要介紹了react.js create-react-app中添加less支持的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11解決React?hook?'useState'?cannot?be?called?in?
這篇文章主要為大家介紹了React?hook?'useState'?cannot?be?called?in?a?class?component報錯解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12React Hooks獲取數(shù)據(jù)實現(xiàn)方法介紹
這篇文章主要介紹了react hooks獲取數(shù)據(jù),文中給大家介紹了useState dispatch函數(shù)如何與其使用的Function Component進(jìn)行綁定,實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10React Hooks: useEffect()調(diào)用了兩次問題分析
這篇文章主要為大家介紹了React Hooks: useEffect()調(diào)用了兩次問題分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11