当前位置: 首页 > 工具软件 > C++React > 使用案例 >

React Native和原生iOS Objective-C的交互解决方案

张和颂
2023-12-01

参考这篇官方文章:Native Modules

用一个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];
    }
}



 类似资料: