2

我对 React 还是很陌生,我基本上会有一个服务(一个实例),我可以以某种方式注入并在多个 React 组件中使用它。

到目前为止,我通过谷歌搜索遇到的选项是:

  • 使用 React 的上下文,但不推荐,因为它是一个未记录的 API。
  • 在 props 中传递对象,从组件到组件,但感觉有点不优雅和乏味
  • 使用 IoC 容器,例如 inversifyJS,看起来很棒,只是它依赖于 typescript,我不希望用 typescript 编写我的 React 应用程序。

现在,Inversify 显然可以在 vanilla JS 中使用inversify-vanillajs-helpers,但是当我尝试在 React 中使用它来解析组件(我的App组件)时,它一直抛出异常说明

“缺少必需的 @injectable 注释:ReactComponent”

所以,我试图找出一种方法来获取我的服务实例(在使用它的几个组件之间共享相同的实例),或者通过使用 React 但没有打字稿,或者我没有的新方法还没有探索。

有任何想法吗 ?

4

1 回答 1

0

There are a few things that you can do if you don't like TypeScript:

First, you are going to need the inversify.decorate method.

Second, this method is probably going to be too verbose for you. We created a helper called inversify-vanillajs-helpers for that reason.

And third, React doesn't play nicely with constructor injection so we created a helper to facilitate lazy property injection called inversify-inject-decorators.

Those three tools should lead yo to the desired result :)

于 2017-02-04T17:11:33.347 回答