【问题标题】:Accessing a React Native module from other native code从其他原生代码访问 React Native 模块
【发布时间】:2015-12-07 18:08:02
【问题描述】:

我使用native module,它非常适合在 React Native 中的 JS 代码中获取设备信息。我还想在其他本机(Objective-C)代码中使用它的功能。

是否可以从其他原生代码访问 React Native 自定义模块的功能?

【问题讨论】:

    标签: ios objective-c react-native


    【解决方案1】:

    您可以直接访问该功能(使用-[RNDeviceInfo deviceName] 方法)或使用 React Native 访问它的方式,即:

    RNDeviceInfo *rn = [[RNDeviceInfo alloc] init];
    NSLog(@"Device Name: %@", [rn constantsToExport][@"model"]);
    

    【讨论】:

    • 为了完善这一点,this 也可以工作,我认为通过不实例化相关类的第二个副本来减少开销。在 AppDelegate _bridge = rootView.bridge; 中保存对桥的引用,然后通过它访问模块 NSString *deviceName = [_bridge.modules[@"RNDeviceInfo"] constantsToExport][@"model"];。注销:NSLog(@"Device Name: %@", deviceName);
    • 你跟我一起学习吧。由于 bridge.modules 的弃用以支持延迟加载模块 NSString *deviceName = [[_bridge moduleForName:@"RNDeviceInfo"] constantsToExport][@"model"];,此调用现已更改
    【解决方案2】:

    我找到了一个解决方案,诚然这有点麻烦。它确实有效,但我认为这远非理想。

    在使用此代码的类的顶部:

    @interface RNDeviceInfo ()
    - (NSString*) deviceName;
    @end
    

    然后我可以这样使用它:

    RNDeviceInfo *rn = [[RNDeviceInfo alloc] init];
    NSLog(@"Device Name: %@", [rn deviceName]);
    

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 1970-01-01
      • 2018-02-23
      • 2015-12-18
      • 2021-07-22
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多