我在github上更新了我学习react-native的一些心得和小技巧,下面的这个例子也在里面,如果现在的项目不忙,基本每天都会更新,希望可以帮助到各位读者。react-native-learn
http://www.jianshu.com/p/2baeac04275e
前端时间写过两篇关于在原生iOS项目中新建react-native页面,并跳转到原生的文章,但昨天有人问我怎么从原生的react-native项目中跳转到自动生成的iOS页面里。
react-native项目.png我就研究了一下,发现其实这个跳转和之前的跳转流程基本是一样的。 这个例子在我的github项目3中
如果想从react-native中跳转到自带的原生页面,首要的问题就是跳转,怎么跳转。 在react-native中提供给了我们Navigator这个组件,而原生的iOS也提供了UINavigationController,所以想要跳转,我们就需要用到这两个东西啦。
Navigator 这个是react-native提供给我们跳转其他页面的组件,需要在react-native项目中引入Navigator <View style={{ flex: 1 }}> <Navigator initialRoute={{ name: 'Root', component: Root }} style={{height:64}} configureScene={(route) => { if (route.sceneConfig) { return route.sceneConfig; } return Navigator.SceneConfigs.PushFromRight; } } renderScene={(route, navigator) => { let Component = route.component; return ( <Component navigator = {navigator} route = {route} {...route.passProps} /> )} } /> </View>关于react-native中Navigator使用的文章网上有很多,我在这里就不多写了,可能以后会写篇文章说一下我对Navigator的理解。
UINavigationController 这个是原生iOS开发中用到最多的控件,每次跳转的时候都会用到它,但我们是想要从react-native跳转到这个里面,所以需要在原生的项目中将rootViewController设置为UINavigationControllerAppDelegate.h
// 创建一个原生的导航条 @property (nonatomic, strong) UINavigationController *nav;AppDelegate.m
// 初始化Nav _nav = [[UINavigationController alloc]initWithRootViewController:rootViewController]; self.window.rootViewController = _nav;上面是我的项目修改后的项目目录,其中蓝色部分是我要跳转的页面,红色部分是我告诉react-native跳转的方法。
PushNative.h中
#import <Foundation/Foundation.h> // 导入RCTBridgeModule类,这个是react-native提供 #import "RCTBridgeModule.h" // 遵守RCTBridgeModul协议 @interface PushNative : NSObject<RCTBridgeModule> @endPushNative.m中
#import "PushNative.h" #import "RCTBridge.h" // 导入跳转的页面 #import "TestController.h" // 导入AppDelegate,获取UINavigationController #import "AppDelegate.h" @implementation PushNative RCT_EXPORT_MODULE(PushNative) // RN跳转原生界面 // RNOpenOneVC指的就是跳转的方法,下面会用到 RCT_EXPORT_METHOD(RNOpenOneVC:(NSString *)msg){ NSLog(@"RN传入原生界面的数据为:%@",msg); //主要这里必须使用主线程发送,不然有可能失效 dispatch_async(dispatch_get_main_queue(), ^{ TestController *one = [[TestController alloc]init]; AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; [app.nav pushViewController:one animated:YES]; }); } TestController类 self.navigationItem.title = @"我是原生页面哟~";完成上面的步骤之后,只需要最后一步就可以成功的跳转啦!
学习react-native也好几个月了,这段时间也是踩坑无数,但学习的过程中也是一个成长的过程,我很喜欢这个感觉。如果大家有什么问题,可以在简书里面评论,也可以私信我。 ps:之前没下简书这个软件,所以之前文章的评论都没怎么看,但我昨天下了一个。