React Native和原生iOS Objective-C的互動解決方案
阿新 • • 發佈:2018-12-31
用一個RCTRootView作為iOS裡一個Controller的view。在RN層的左上角返回按鈕點選後pop回iOS層。發現無法執行,除錯發現controller的navigationCont的值是空的。發現與RN互動的這個self地址和iOS層的self並不是同一個記憶體地址,RN應該是deep copy了iOS層的self等,導致無法進行pop。
有一種解決方案:寫一個單例TCReactNativeBridge,專門給用來處理原生和React
Native之間的互動,TCReactNativeBridge暴露一個delegate給需要互動的原生Controller,用來接收React Native傳遞過來的事件和引數,並用回撥的方式傳回引數給React Native。
#import "RCTBridgeModule.h" @protocol TCReactNativeBridgeDelegate <NSObject> @optional -(void)rn_leftBarButtonClicked; -(void)rn_rightBarButtonClicked; -(void)rn_reciveFromReactNative:(NSString*)action paramas:(NSArray*)paramas callback:(RCTResponseSenderBlock)callback; @end @interface TCReactNativeBridge : NSObject<RCTBridgeModule> @property (nonatomic,weak) id<TCReactNativeBridgeDelegate> delegate; +(instancetype)sharedIncetance; @end
@implementation TCReactNativeBridge RCT_EXPORT_MODULE() +(instancetype)sharedIncetance { static TCReactNativeBridge *incetance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^ { incetance = [[TCReactNativeBridge alloc] init]; }); return incetance; }
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>
<span style="font-family: Arial, Helvetica, sans-serif;">-(void)rn_reciveFromReactNative:(NSString*)action</span>
paramas:(NSArray*)paramas
callback:(RCTResponseSenderBlock)callback
{
if ([action isEqualToString:@"hideTabbar"]) {
[[TCGlobal sharedIncetance].tabBarController setTabBarHidden:YES animated:YES];
}
else if ([action isEqualToString:@"showTabbar"]) {
[[TCGlobal sharedIncetance].tabBarController setTabBarHidden:NO animated:YES];
}
else if ([action isEqualToString:@"motherForumBoardCreateNewPost"]) {
TMCreateMotherForumPostViewController *c = [[TMCreateMotherForumPostViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:c];
[self presentViewController:nav animated:YES completion:nil];
}
}
在需要和React Native互動的地方接收delegate
-(void)rn_reciveFromReactNative:(NSString*)action
paramas:(NSArray*)paramas
callback:(RCTResponseSenderBlock)callback
{
if ([action isEqualToString:@"hideTabbar"]) {
[[TCGlobal sharedIncetance].tabBarController setTabBarHidden:YES animated:YES];
}
else if ([action isEqualToString:@"showTabbar"]) {
[[TCGlobal sharedIncetance].tabBarController setTabBarHidden:NO animated:YES];
}
}