今天學習一下怎麼在React Native項目中集成iOS原生模塊,道理和在iOS原生項目中集成React Native模塊相似.他們的界面跳轉靠的都是iOS原生的UINavigationController.react
iOS原生端:git
1.AppDelegate.hgithub
1 // 建立一個原生的導航條 2 @property (nonatomic, strong) UINavigationController *nav;
AppDelegate.mreact-native
修改部分代碼:app
1 // 初始化Nav 2 _nav = [[UINavigationController alloc]initWithRootViewController:rootViewController]; 3 4 self.window.rootViewController = _nav;
2.新建一個UIViewController便可.async
3.新建類PushNative,繼承NSObject,遵循.實現RCTBridgeModule協議,引入相關類. 學習
PushNative.h測試
1 // 2 // PushNative.h 3 // RNAddNative 4 // 5 // Created by Shaoting Zhou on 2017/2/22. 6 // Copyright © 2017年 Facebook. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 #import <React/RCTBridgeModule.h> 11 #import <React/RCTLog.h> 12 @interface PushNative : NSObject<RCTBridgeModule> 13 14 @end
PushNative.hthis
1 // 2 // PushNative.m 3 // RNAddNative 4 // 5 // Created by Shaoting Zhou on 2017/2/22. 6 // Copyright © 2017年 Facebook. All rights reserved. 7 // 8 9 #import "PushNative.h" 10 #import "TestController.h" 11 #import "AppDelegate.h" 12 @implementation PushNative 13 RCT_EXPORT_MODULE(); 14 // 接收傳過來的 NSString 15 RCT_EXPORT_METHOD(RNOpenOneVC:(NSString *)name){ 16 NSLog(@"%@", name); 17 //跳轉界面 18 //主要這裏必須使用主線程發送,否則有可能失效 19 dispatch_async(dispatch_get_main_queue(), ^{ 20 TestController *one = [[TestController alloc]init]; 21 22 AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 23 24 [app.nav pushViewController:one animated:YES]; 25 }); 26 } 27 @end
RN端:atom
引入NativeModules,InteractionManager
var Push = NativeModules.PushNative; //這個PushNative就是原生中的PushNative類
而後在點擊方法裏面寫入
Push.RNOpenOneVC('測試'); //這個RNOpenOneVC()就是原生中的PushNative類中的方法
完整代碼以下:
1 import React, { Component } from 'react'; 2 import { 3 AppRegistry, 4 StyleSheet, 5 Text, 6 View, 7 NativeModules, 8 InteractionManager 9 } from 'react-native'; 10 var Push = NativeModules.PushNative; 11 12 export default class RNAddNative extends Component { 13 render() { 14 return ( 15 <View style={styles.container}> 16 <Text style={styles.welcome}> 17 我是RN界面 18 </Text> 19 <Text style={styles.instructions} onPress={()=>this.btnOnclick()}> 20 push到iOS原生界面 21 </Text> 22 </View> 23 ); 24 } 25 btnOnclick =() =>{ 26 InteractionManager.runAfterInteractions(()=> { 27 Push.RNOpenOneVC('測試'); 28 }); 29 } 30 }
演示效果+源碼參考: https://github.com/pheromone/IOS-native-and-React-native-interaction 中的RNAddNative.zip