React Native-将数据从Native发送到javascript/桥接



我是React Native(iOS)的新手,我读了很多关于桥接的文章,但我似乎无法做到这一点。

我需要能够将对象/字符串从AppDelegate发送到JavaScript。我的AppDelegate返回一个UserName,该UserName由AppDelegade中我的一个方法中的本机代码检索。

我尝试在AppDelegate.m 中使用

#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

然后

@synthesize bridge = _bridge;

在我的方法中

  NSString *eventName = notification.userInfo[@"name"];
  [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder"
                                               body:@{@"name": eventName}];

但以上都不起作用,我也会出错。我也需要对AppDelegate.h做些什么吗?

有人能帮我吗?将数据从本机发送到javascript的最简单方法是什么?

更新:

我找到了一个变通方法,但我认为它无效,因为我已经打了两次RCTRootView。首先用initialProperties nil加载应用程序,如下所示:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

 jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"myApp"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  [self getUsername];
}

当我第二次检索用户名时,我会更新initialProperties,如下所示:

-(void) getUsername {
    //3rd party code to retrieve the username
            NSString *username = username
      NSURL *jsCodeLocation;
      jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
      RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:jsCodeLocation moduleProvider:nil launchOptions:nil];
      RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                       moduleName:@"myApp"
                                                initialProperties: @{@"username" : username}];

      self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
      UIViewController *rootViewController = [UIViewController new];
      rootViewController.view = rootView;
      self.window.rootViewController = rootViewController;
      [self.window makeKeyAndVisible];

}

通过以上方式,我可以通过JavaScript中的this.props发送和接收用户名。

但正如我所说,我不确定这是一种有效的方式,因为我已经打了两次RCTRootView

请提供任何帮助。

您可以将它放在本机模块中,而不是试图将其放在iOS端的初始启动代码中,您可以导出一个函数来返回其中的信息。请参阅React Natives官方文档:https://facebook.github.io/react-native/docs/native-modules-ios.html

最新更新