将数据从React Native导出到Native

时间:2017-01-05 18:25:25

标签: android ios react-native

我有许多组件正在集成到Android和iOS应用程序中,并且希望有一些与React Native代码一起生成的元数据,这些代码可以为应用程序提供有关组件之前的一些信息装载

本机React Native框架允许通过"本机模块注入常量和函数,"可以全局访问而不必绑定到组件,活动,视图控制器等。基本上,我们可以轻松地发送数据Native => React Native。

是否有一种简单的方法可以从React Native =>中做同样的事情。本机,就像暴露一个常量或一个可以通过本机应用程序通过React桥/上下文访问的函数?

1 个答案:

答案 0 :(得分:0)

我需要将一些数据从React Native传递给Native(iOS),因为我已经使用了Notifications。可能这可以帮助一些人。

在React Native文件中导入NativeModule

import {
  StyleSheet,
  AppRegistry,
  Text,
  TextInput,
  View,
  NavigatorIOS,
  Button,
  ActivityIndicator,
  TouchableHighlight,
  FlatList,
  NativeModules
} from 'react-native';

const NotificationsModule = NativeModules.NotificationsModule;

然后在需要时添加通知

创建您要发送的数据字典

const params = { "yourKey": "value"};

NotificationsModule.sendNotification("OrderLoaded", yourParams);
Then go in your xcode and add create NotificationsModule file

您的NotificationsModule.h文件

#import <Foundation/Foundation.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@interface NotificationsModule : NSObject

@end

您的NotificationsModule.m文件

#import <React/RCTConvert.h>
#import <React/RCTLog.h>
#import <React/RCTBridgeModule.h>
@interface NotificationsModule : NSObject<RCTBridgeModule>
@end

@implementation NotificationsModule

RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(sendNotification:(NSString*)notification params:(NSDictionary*)params) {
    if ([notification isCaseInsensitiveEqualToString:@"OrderLoaded"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"OrderLoaded" object:nil userInfo:params];
    }
}


@end

通过在您希望了解更改的控制器中添加以下行来观察更改

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(OrderLoaded:) name:@"OrderLoaded" object:nil];

最后你的方法

- (void)OrderLoaded:(NSNotification*)notification
{
    NSMutableDictionary *dictionary = [notification.userInfo mutableCopy];

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        NSString *yourData = [dictionary valueForKey:@"yourKey"];
        // Do your stuff with yourData           
    });
}