ios - React Native 模块中的依赖注入(inject)

标签 ios dependency-injection react-native

我们正在逐步将我的应用程序转换为 React Native。 我一直在 iOS 上的 React Native 中遇到依赖注入(inject)问题。

我的应用程序中有一些服务,我想在 native 模块中使用。目前,它们是通过 Typhoon 注入(inject)的,一切正常。

然而,react native 本身会将任何 native 模块初始化和维护为一个单例。这阻止了我让 Typhoon 初始化它们,所以我不能向它们注入(inject)依赖项。

可以做什么?自己创建 RCTBridge 是一个选项,但感觉很底层,仍然需要首先弄清楚如何将它注入(inject)到 UIView 中。

最佳答案

我不确定为什么您的问题没有获得更多赞成票;我自己也在努力回答同样的问题,我想我应该跳上去回答我的第一个 StackOverflow 问题!

RCTBridge class 周围挖掘提供了答案。您需要做的是使用实现 RCTBridgeProtocol 的类的实例手动初始化 RCTBridge(重要的是方法“extraModulesForBridge”;如果需要,您甚至可以在 View Controller 中实现此协议(protocol)。

// Initialise a class that implements RCTBridgeDelegate
// Be warned, RCTBridge won't store a strong reference to your delegate.
// You should there store this delegate as a property of your initialising class, or implement the protocol in the View Controller itself. 
id<RCTBridgeDelegate> moduleInitialiser = [[classThatImplementsRCTBridgeDelegate alloc] init];

// Create a RCTBridge instance 
// (you may store this in a static context if you wish to use with other RCTViews you might initialise.  
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:moduleInitialiser launchOptions:nil];

// Initialise an RCTRootView
RCTRootView *rootView = [[RCTRootView alloc]
                     initWithBridge:bridge
                         moduleName:kModuleName
                  initialProperties:nil];

// Note that your class that implements RCTBridgeDelegate SHOULD implement the following methods and it might look something like this.

// This will return the location of our Bundle
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
    return [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
}

// Importantly, this is the method we need to implement to answer this question
// We must return an array of initialised Modules
// Be warned, I am writing this off of the top of my head, so excuse any syntax errors there might be!
- (NSArray *)extraModulesForBridge:(RCTBridge *)bridge
{
   return @[[OurNativeModule alloc] initWithCustomInitialiser:customDependency]];
}

编辑:我将其添加到 React-native 文档中。 https://facebook.github.io/react-native/docs/native-modules-ios.html#dependency-injection

关于ios - React Native 模块中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37142310/

相关文章:

c# - 如何使用 Simple Injector 注册命名实例

javascript - NodeJS/重新验证 : How can I recieve file upload in API?

ios - 在 iOS 7 中,如何访问 Interface Builder 中的 topLayoutGuide/bottomLayoutGuide?

ios - 将传递给方法的选择器分配为按钮目标操作

unit-testing - Ember 路线单元测试中未知的 `service:session` 注入(inject)器

java - Spring:为什么我们 Autowiring 接口(interface)而不是实现的类?

javascript - Reactjs 将 key prop 分配给数组渲染组件

react-native - react : Calling JS function after bridge has been destroyed --- How to find which function

ios - 如何从iCloud或其他服务器加载内容到App中的viewController

ios - SwiftUI @State 枚举即使在赋值后仍然为 nil