如何在 React 中声明一个全局变量? [英] How to declare a global variable in React?

查看:52
本文介绍了如何在 React 中声明一个全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在组件(应用程序中加载的第一个组件)中初始化了一次 i18n 翻译对象.在所有其他组件中都需要相同的对象.我不想在每个组件中重新初始化它.有什么办法?使其可用于窗口范围无济于事,因为我需要在 render() 方法中使用它.

I initialized i18n translation object once in a component (a first component that loads in the app ). That same object is required In all other components. I don't want to re-initialize it in every component. What's the way around? Making it available to window scope doesn't help as I need to use it in the render() method.

请为这些问题提出一个通用的解决方案,而不是 i18n 特定的解决方案.

Please suggest a generic solution for these problems and not i18n specific solution.

推荐答案

为什么不尝试使用 Context?

您可以在任何父组件中声明一个全局上下文变量,并且可以通过 this.context.varname 在整个组件树中访问该变量.您只需要在父组件中指定 childContextTypesgetChildContext ,然后您可以通过在父组件中指定 contextTypes 从任何组件使用/修改它子组件.

You can declare a global context variable in any of the parent components and this variable will be accessible across the component tree by this.context.varname. You only have to specify childContextTypes and getChildContext in the parent component and thereafter you can use/modify this from any component by just specifying contextTypes in the child component.

但是,请注意文档中提到的这一点:

However, please take a note of this as mentioned in docs:

正如在编写清晰的代码时最好避免使用全局变量一样,在大多数情况下您应该避免使用上下文.特别是,在使用它来节省输入"并使用它而不是传递显式 props 之前,请三思.

Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.

这篇关于如何在 React 中声明一个全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆