不是原创,官方文档其实已经说的很清楚了,这里只是总结一下。
1.直接调用并回调js方法
这类主要是针对耗时比较长的场景使用,通过RCTResponseSenderBlock进行回调。
ios原生端的demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | RCT_EXPORT_METHOD(getSSID:(RCTResponseSenderBlock)callback) { NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces()); NSLog(@"%s: Supported interfaces: %@", __func__, interfaceNames); NSDictionary *SSIDInfo; NSString *SSID = @"error"; for (NSString *interfaceName in interfaceNames) { SSIDInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName)); if (SSIDInfo.count > 0) { SSID = SSIDInfo[@"SSID"]; break; } } callback(@[SSID]); } |
react-native端调用
1 2 3 4 5 6 7 8 9 10 | NetworkInfo.getIPAddress(ip => { localIp = ip; console.log(ip); AlertIOS.alert( 'IP地址:' + localIp, [ {text : '关闭', onPress : () => console.log('123')} ] ) }); |
这种回调方式,必须得直接调用方法,但是某些情况下,我们的原生端本身就是回调函数,直接调用的方法默认了回调的实现,此时返回的结果是不能直接回调得到,所以react-native 提供的另外一种回调实现。
2.监听队列回调
ios原生端
1 2 3 4 5 6 7 8 9 10 11 | #import "RCTBridge.h" #import "RCTEventDispatcher.h" @implementation CalendarManager @synthesize bridge = _bridge; - (void)calendarEventReminderReceived:(NSNotification *)notification { NSString *eventName = notification.userInfo[@"name"]; [self.bridge.eventDispatcher sendAppEventWithName:@"EventReminder" body:@{@"name": eventName}]; } @end |
react-native端
1 2 3 4 5 6 | var subscription = DeviceEventEmitter.addListener( 'EventReminder', (reminder) => console.log(reminder.name)); ... // Don't forget to unsubscribe subscription.remove(); |
这种回调是基于原生端默认实现了回调函数,所以,我们在react native无法直接调用该回调函数进行react-native端的回调,所以建立了一个回调队列,并在react-native监听该队列进行回调。
转载请注明:迷路的老鼠 » react-native原生回调的两种方式之IOS