How to declare a global variable in React?

前端 未结 9 1248
自闭症患者
自闭症患者 2020-11-29 23:21

I initialized i18n translation object once in a component ( first component that loads in the app ) . That same object is required In all other components. I do

9条回答
  •  星月不相逢
    2020-11-29 23:57

    Why don't you try using Context?

    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:

    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.

提交回复
热议问题