美文网首页React NativeReact-NativeiOS混合开发
在iOS中创建React-Native页面,并跳转到原生页面

在iOS中创建React-Native页面,并跳转到原生页面

作者: 挂着铃铛的兔 | 来源:发表于2016-09-02 17:28 被阅读2135次

    需求:

    上一篇文章中,我们讲到怎么在iOS原生里面集成React-Native,这篇文章将讲解怎么在原生中创建React-Native页面,并且从RN页面跳转到原生页面。
    我将项目更新到了github上,里面有很多我自己的理解,希望可以帮到各位读者react-native-learn

    如果遇到什么问题可以在评论区回复,或者加QQ群397885169讨论

    创建:

    我们将在项目中创建一个View,用来展示React-Native页面

    • 在原生ios应用添加容器视图 我们在工程文件下创建一个名为ReactView的UIView文件: React-iOS目录 -> 右键 -> New File -> Cocoa Touch Class -> ReactView
    ReactView.png
    • 修改ReactView.m
    #import "ReactView.h"
    #import <RCTRootView.h>
    @implementation ReactView
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            NSString * strUrl = @"http://localhost:8081/index.ios.bundle?platform=ios&dev=true";
            NSURL * jsCodeLocation = [NSURL URLWithString:strUrl];
            // 这里的moduleName一定要和下面的index.ios.js里面的注册一样
            RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                                 moduleName:@"ReactiOS"
                                                          initialProperties:nil
                                                              launchOptions:nil];
            
            [self addSubview:rootView];
            
            rootView.frame = self.bounds;
        }
        return self;
    }
    @end
    

    ReactView.m中通过http://localhost:8081/index.ios.bundle?platform=ios&dev=true加载bundle文件,由RCTRootView解析转化原生的UIView,然后通过initWithFrame将frame暴露出去。

    • 在原生ios应用中引用ReactView 上面我们创建了一个ReactView,打开ViewController.m,在viewDidLoad方法中应用我们的ReactView。
    #import "ViewController.h"
    #import "ReactView.h"
    @interface ViewController ()
    @end
    @implementation ViewController
     - (void)viewDidLoad {
          [super viewDidLoad];
          ReactView * reactView = [[ReactView alloc] initWithFrame:CGRectMake(0,64,CGRectGetWidth(self.view.bounds), 100)];
        
          [self.view addSubview:reactView];
      }
    

    这样,我们的项目就创建好了。接下来就是运行项目了

    运行:

    如果做过reactNative开发,都知道每次运行项目之前都需要启动开发服务器,只不过之前是X-Code自动启动,现在需要手动开启。
    进入reactnative根目录(我是放在桌面上了,最简单的方式就是直接拖拽),然后启动$ react-native start

    开启服务器.png

    设置允许Http请求:

    直接运行项目会报Could not connect to development server错误
    解决方式:打开info.plist文件,添加下面配置即可:

    <key>NSAppTransportSecurity</key>  
    <dict>  
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict> 
    

    运行ios项目:

    通过Xcode点击项目或者command + R运行项目,如果顺利的话,就会看到成功运行的界面:

    运行成功.png

    当看到上面的图片,就代表大功告成,这样就掌握了在iOS原生中集成React-Native方法了~

    跳转:

    接下来,我们讲讲怎么从上面创建的RN页面点击Hello World !跳转回原生页面
    ps:官方文档对于iOS和原生的交互写了好多,不知道你们看懂没,反正我是一头雾水。
    还是直接上代码:

    • 在OC中的代码
       1. 在XCode 中的AppDelegate.h中创建原生的UINavigationController,这样在其他页面可以用过AppDelegate这个单例来调用到导航进行跳转操作
    #import <UIKit/UIKit.h>
    @interface AppDelegate : UIResponder <UIApplicationDelegate>
    
    @property (strong, nonatomic) UIWindow *window;
    // 创建一个原生的导航条
    @property (nonatomic, strong) UINavigationController *nav;
    @end
    

    2.在AppDelegate.m中使导航条成为跟控制器

    #import "AppDelegate.h"
    #import "ViewController.h"
    @interface AppDelegate ()
    @end
    @implementation AppDelegate
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        
        self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        self.window.backgroundColor = [UIColor whiteColor];    
        ViewController *view = [[ViewController alloc]init];
        // 初始化Nav
        _nav = [[UINavigationController alloc]initWithRootViewController:view];
        // 将Nav设置为根视图
        self.window.rootViewController = _nav;    
        [self.window makeKeyAndVisible];    
        return YES;
    }
    

    3.新建 RCTModules 类,继承 NSObject 封装一个方法使用“通知”进行消息的传送从而实现页面的跳转

    RCTModules.h

    #import <Foundation/Foundation.h>
    #import "RCTBridgeModule.h"
    
    @interface RTModule : NSObject<RCTBridgeModule>
    @end
    

    RCTModules.m

    #import "RTModule.h"
    #import "RCTBridge.h"
    
    @implementation RTModule
    
    RCT_EXPORT_MODULE(RTModule)
    //RN跳转原生界面
    RCT_EXPORT_METHOD(RNOpenOneVC:(NSString *)msg){
        
        NSLog(@"RN传入原生界面的数据为:%@",msg);
        //主要这里必须使用主线程发送,不然有可能失效
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"RNOpenOneVC" object:nil];
        });
    }
    
    @end
    

    4.接下来在ViewController.m中添加通知的方法

    #import "ViewController.h"
    #import "ReactView.h"
    #import "AppDelegate.h"
    #import "OneViewController.h"
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.navigationItem.title = @"我是包含RN的原生页面哟~";
    
        ReactView * reactView = [[ReactView alloc] initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.bounds), 100)];
        
        [self.view addSubview:reactView];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doPushNotification:) name:@"RNOpenOneVC" object:nil];
    
    }
    
    - (void)doPushNotification:(NSNotification *)notification{
        NSLog(@"成功收到===>通知");
        OneViewController *one = [[OneViewController alloc]init];
        
        AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        
        [app.nav pushViewController:one animated:YES];
        
        //注意不能在这里移除通知否则pus进去后有pop失效
    }
    
    @end
    

    5.接下来就要创建我们将要跳转的页面啦。创建OneViewController继承于UIViewController

    OC中的项目结构.png
    • 在index.ios.js中的代码
    import React, { Component } from 'react';
    import {  
        AppRegistry, 
        StyleSheet,  
        Text,  
        View, 
        TouchableOpacity,  
        NativeModules
    } from 'react-native';
    var RNModules = NativeModules.RTModule;
    class ReactiOS extends Component {
        render() {   
            return (      
                <View style={styles.container}>
                <TouchableOpacity
                   onPress={()=>RNModules.RNOpenOneVC('测试')}>
                       <Text>Hello World!</Text>
                </TouchableOpacity>      </View>    );  
        }
    }
    const styles = StyleSheet.create({ 
      container: {
        backgroundColor : 'red',
        height:100,
        flexDirection : 'row'
        },
    });
    AppRegistry.registerComponent('ReactiOS', () => ReactiOS);
    

    运行:

    上面的那些步骤写完,开启服务器就应该能看到下面这张图,点击helloWorld,跳转到下一个页面啦~

    控制台打印.png gif5新文件.gif

    小结:

    通过React-Native与iOS原生的集成步骤和这篇文章,应该能够学会怎么在项目中集成React-Native项目了。当然,你如果想在同一个RN页面中跳转多个页面,可以注册不同的通知,在RN页面点击的时候跳转就可以了。在我的demo中会有这个例子。
    ps:我还是很推荐用Cocoapods集成React-Native开发环境的,因为我手动集成的时候遇到了好多坑,如果在开发中遇到什么其他问题,欢迎评论。
    /(ㄒoㄒ)/~~ 不知道怎么往github上传。。。所以打包成了百度云

    相关文章

      网友评论

      • c4466df7da5f:您好 请问 xcode代码的module name是不是就是react native中registerComponent 的名字?
      • a梦里青草香:楼主你好,请问怎么把创建好的RN代码和写好的原生代码合并到一起呢
        a梦里青草香:@挂着铃铛的兔 是不是实现页面之间的跳转就可以了啊
        a梦里青草香:@挂着铃铛的兔 自己创建的啊,RN是别人写的,我写一个原生的功能,现在要整合到一起
        挂着铃铛的兔:@coderMC 你的主工程是rn自动生成的还是自己创建的?
      • c83a98fa1746:看了你的文章,很清晰。跳到GitHub,又跳到简书,最后用手机简书找到你关注了:smile:
        挂着铃铛的兔:@挥剑下江南 谢谢
      • YxxxHao:为什么要用通知呢,吓到宝宝了:joy: 乱用通知, 后期是没有办法维护的
        YxxxHao:@挂着铃铛的兔 我已经搞定了
        挂着铃铛的兔:@YxxxHao 可以不用呀。可以看一下我写的那个learn里面有不用通知的。
      • Lion_Liu:这个 来回跳转时间是多久?我试了下,最快也要三五秒。。。。。 :scream:
        挂着铃铛的兔:@Lion_Liu 你将跳转方法写在主线程了吗?
      • 溺水的猫:求demo地址
        挂着铃铛的兔:@溺水的猫 https://github.com/RabbitBell/react-native-learn
        挂着铃铛的兔:@溺水的猫 很快就好。
      • bf6662411ce1:这个是一个roorview 如果是不同模块中的 个别view是咋弄的
        挂着铃铛的兔:@丶K神 都是差不多的步骤
      • 59a4604feba5:努力,搞出下篇,老于 :kissing_heart:

      本文标题:在iOS中创建React-Native页面,并跳转到原生页面

      本文链接:https://www.haomeiwen.com/subject/dzxhettx.html