我正在编写一个具有两个 View 的 iOS 应用程序。每个 View 都是一个 RCTRootView,由不同的 React Native 组件创建。
我调查了这个问题 ( Multiple RCTRootView in a single App ),所以现在我明白这是可能的。
但是有个问题。让第一个 RCTRootView 实例为 B,让第二个实例为 B。A 首先显示在屏幕上,其 react native 对应物使用 NativeAppEventEmitter 从我的 native 应用程序接收事件。此时,一切正常。 A还有一个按钮可以在屏幕上显示B。
按下按钮时,将创建并显示 B。再次按下按钮时,B 将从其父 View 中删除并销毁。
但在此之后,NativeAppEventEmitter 什么都不做。
欢迎任何类型的提示或评论。
最佳答案
此问题与 self.bridge 为 nil 的症状有关。虽然我做了@synthesize bridge = _bridge,但是当从javascript端处理事件时,bridge属性为nil,这是出乎意料的。
通过检查和上网,我找到了原因:对于RCTBridgeModule,objective-c代码很难控制对象的生命周期。关于 bridge 模块的最佳实践是忘记有关其生命周期的所有细节,并且不要对其生命周期做出任何假设。
因此,如果您自己创建了桥接模块(可能使用 [MyBridge new]
),您的应用程序中可能会有两个不同的桥接对象。您无法确定哪个对象是从 JavaScript 端接收事件的对象。
因此,我现在正在使用以下解决方案。
@implementation EventBridge
@synthesize bridge = _bridge;
RCT_EXPORT_MODULE();
- (instancetype) init {
self = [super init];
if ( self ) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(cartUpdateNotification:)
name:kCartUpdateNotification
object:nil];
}
return self;
}
+ (void) addObserver:(id)observer selector:(SEL)selector {
[[NSNotificationCenter defaultCenter] addObserver:observer
selector:selector
name:kMenuClickNotification
object:nil];
}
/*
* objc -> js call
*/
+ (void) postEventWithName:(NSString *)name object:(id)object {
[[NSNotificationCenter defaultCenter]
postNotification:[NSNotification notificationWithName:name
object:object]];
}
/*
* js -> objc call when the hamburger is clicked
*/
RCT_EXPORT_METHOD(menuClicked)
{
// This method might be called on the different TopNavViewController object.
[[NSNotificationCenter defaultCenter] postNotificationName:kMenuClickNotification
object:nil];
}
- (void) cartUpdateNotification:(NSNotification*)notification {
[self.bridge.eventDispatcher sendAppEventWithName:@"CartUpdated" body:@{@"item":notification.object}];
}
@end
关于ios - 一个应用程序中的两个 RCTRootView 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552719/