今天学习一下怎么在React Native项目中集成iOS原生模块,道理和在iOS原生项目中集成React Native模块类似.他们的界面跳转靠的都是iOS原生的UINavigationController.

iOS原生端:

1.AppDelegate.h

 // 创建一个原生的导航条
@property (nonatomic, strong) UINavigationController *nav;

AppDelegate.m

修改部分代码:

   // 初始化Nav
_nav = [[UINavigationController alloc]initWithRootViewController:rootViewController]; self.window.rootViewController = _nav;

2.新建一个UIViewController即可.

3.新建类PushNative,继承NSObject,遵循.实现RCTBridgeModule协议,引入相关类.

PushNative.h

 //
// PushNative.h
// RNAddNative
//
// Created by Shaoting Zhou on 2017/2/22.
// Copyright © 2017年 Facebook. All rights reserved.
// #import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTLog.h>
@interface PushNative : NSObject<RCTBridgeModule> @end

PushNative.h

 //
// PushNative.m
// RNAddNative
//
// Created by Shaoting Zhou on 2017/2/22.
// Copyright © 2017年 Facebook. All rights reserved.
// #import "PushNative.h"
#import "TestController.h"
#import "AppDelegate.h"
@implementation PushNative
RCT_EXPORT_MODULE();
// 接收传过来的 NSString
RCT_EXPORT_METHOD(RNOpenOneVC:(NSString *)name){
NSLog(@"%@", name);
//跳转界面
//主要这里必须使用主线程发送,不然有可能失效
dispatch_async(dispatch_get_main_queue(), ^{
TestController *one = [[TestController alloc]init]; AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; [app.nav pushViewController:one animated:YES];
});
}
@end

RN端:

引入NativeModules,InteractionManager

var Push = NativeModules.PushNative;    //这个PushNative就是原生中的PushNative类

然后在点击方法里面写入

Push.RNOpenOneVC('测试');    //这个RNOpenOneVC()就是原生中的PushNative类中的方法

完整代码如下:

 import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
NativeModules,
InteractionManager
} from 'react-native';
var Push = NativeModules.PushNative; export default class RNAddNative extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
我是RN界面
</Text>
<Text style={styles.instructions} onPress={()=>this.btnOnclick()}>
push到iOS原生界面
</Text>
</View>
);
}
btnOnclick =() =>{
InteractionManager.runAfterInteractions(()=> {
Push.RNOpenOneVC('测试');
});
}
}

演示效果+源码参考:  https://github.com/pheromone/IOS-native-and-React-native-interaction  中的RNAddNative.zip




04-20 17:23