如何在 React Native 中使用全局变量? [英] How to use global variables in React Native?

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

问题描述

在 React Native 中,我想在不同屏幕之间移动时使用全局变量

In React Native I want to use global variables when I am moving between different screens

谁能帮我实现它?

推荐答案

React Native 中的全局作用域是全局变量.比如global.foo = foo,那么就可以在任何地方使用global.foo.

The global scope in React Native is variable global. Such as global.foo = foo, then you can use global.foo anywhere.

但不要滥用它!在我看来,全局范围可能用于存储全局配置或类似的东西.在不同视图之间共享变量,作为您的描述,您可以选择许多其他解决方案(使用 redux、flux 或将它们存储在更高的组件中),全局范围不是一个好的选择.

But do not abuse it! In my opinion, global scope may used to store the global config or something like that. Share variables between different views, as your description, you can choose many other solutions(use redux,flux or store them in a higher component), global scope is not a good choice.

定义全局变量的一个好习惯是使用 js 文件.例如 global.js

A good practice to define global variable is to use a js file. For example global.js

global.foo = foo;
global.bar = bar;

然后,确保它在项目初始化时执行.例如在 index.js 中导入文件:

Then, to make sure it is executed when project initialized. For example, import the file in index.js:

import './global.js'
// other code

现在,你可以在任何地方使用全局变量,不需要在每个文件中导入 global.js.尽量不要修改它们!

Now, you can use the global variable anywhere, and don't need to import global.js in each file. Try not to modify them!

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

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