react-native使用react-native-tab-navigator底部導(dǎo)航器,需要實(shí)現(xiàn)Tab導(dǎo)航器切換rn視圖和native原生視圖。
參考rn官網(wǎng):http://reactnative.cn/docs/0.41/native-component-ios.html#content 提煉整理出以下內(nèi)容。
1、IOS本地文件
創(chuàng)建類RNChatViewManager,.h文件和.m文件代碼如下,其中ChatContactViewController為將要展示的原生視圖控制器。
// RNChatViewManager.h
#import "RCTViewManager.h"
#import "ChatContactViewController.h"
@interface RNChatViewManager : RCTViewManager
@property (nonatomic, strong) ChatContactViewController *chatContactVC;
@end
// RNChatViewManager.m
#import "RNChatViewManager.h"
@implementation RNChatViewManager
RCT_EXPORT_MODULE()
- (UIView *)view{
_chatContactVC = [[ChatContactViewController alloc] init];
return _chatContactVC.view;
}
@end
2、RN代碼配置
需要導(dǎo)入requireNativeComponent來(lái)加載Native組件
RNChatView即調(diào)用了Native工程中創(chuàng)建的RNChatViewManager類。
注意寫法:RNChatView即表示RNChatViewManager類
不可修改為requireNativeComponent('RNChatViewManager', ChatView)
import React, { Component, PropTypes } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
requireNativeComponent,
} from 'react-native';
var OCChatView = requireNativeComponent('RNChatView', ChatView);
export default class ChatView extends Component {
static propTypes = {
color: PropTypes.string,
};
render(){
return(
<OCChatView {...this.props} />
);
}
}
3、注意事項(xiàng)
以上配置即可以實(shí)現(xiàn)rn導(dǎo)航器在js頁(yè)面與oc頁(yè)面之間相互切換了,但是會(huì)出現(xiàn)點(diǎn)擊oc頁(yè)面上的push跳轉(zhuǎn)操作時(shí)無(wú)反應(yīng)。這是因?yàn)镽N跳轉(zhuǎn)Native時(shí)需要在主線程中執(zhí)行,而默認(rèn)是在輔線程中。
// 執(zhí)行跳轉(zhuǎn)
//自定義宏IS_USING_REACT_NATIVE區(qū)分是否來(lái)自RN的跳轉(zhuǎn)操作
if (IS_USING_REACT_NATIVE) {
[AppDelegate RNPushViewControllerWith:vc];
}else{
[self.navigationController pushViewController:vc animated:YES];
}
// 封裝在appDelegate.m
// 在主線程push跳轉(zhuǎn),否則無(wú)效
+ (void)RNPushViewControllerWith:(UIViewController *)vc{
dispatch_async(dispatch_get_main_queue(), ^{
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[app.nav pushViewController:vc animated:YES];
});
}