React NativeReact-NativeiOS混合开发

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

2016-09-02  本文已影响2135人  挂着铃铛的兔

需求:

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

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

创建:

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

ReactView.png
#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暴露出去。

#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和原生的交互写了好多,不知道你们看懂没,反正我是一头雾水。
还是直接上代码:

#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
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上传。。。所以打包成了百度云

上一篇下一篇

猜你喜欢

热点阅读