我有许多组件正在集成到Android和iOS应用程序中,我希望有一些元数据与React一起使用,这些元数据在安装/加载之前向应用程序提供了一些关于组件的信息。
本机React本机框架允许通过“本机模块”注入常量和函数,这些模块可以全局访问,而无需绑定到组件、活动、视图控制器等。基本上,我们可以轻松地发送数据本机=> React本机。
是否有一种简单的方法可以从中实现相同的操作,比如公开一个常量或函数,这些常量或函数可以通过本机应用程序通过=>桥/上下文访问?
发布于 2018-03-22 11:17:05
我需要从React原住民(IOS)传递一些数据,因为我使用了通知。也许这能帮到一个人。
将NativeModules导入您的React本机文件中
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
});
}https://stackoverflow.com/questions/41492090
复制相似问题