且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React Native中的全局变量/常量

更新时间:2023-11-14 08:46:46

我做的是创建一个全局模块......

What' I've done is create a globals module...

/ / File:Globals.js

// File: Globals.js

module.exports = {
  STORE_KEY: 'a56z0fzrNpl^2',
  BASE_URL: 'http://someurl.com',
  COLOR: {
    ORANGE: '#C50',
    DARKBLUE: '#0F3274',
    LIGHTBLUE: '#6EA8DA',
    DARKGRAY: '#999',
  },
};

然后我只需要顶部...

Then I just require it at the top...

const GLOBAL = require('../Globals');

然后像这样访问它们......

And access them like so...

GLOBAL.COLOR.ORANGE



_____________________



2018年2月10日更新



这似乎是一个非常受欢迎且有用的答案,所以我想我应该更新它使用更新的语法。以上仍然可以在CommonJS模块系统中运行,但是现在你几乎可能遇到ES6和 import 模块,而不是 require 他们。

_____________________

UPDATE on Feb 10, 2018

This seems to be a pretty popular and useful answer, so I thought I should update it with the more current syntax. The above still works in CommonJS module systems, but now days you're just as likely to run into ES6 and importmodules rather than require them.

//文件:Globals.js

// File: Globals.js

export default {
  STORE_KEY: 'a56z0fzrNpl^2',
  BASE_URL: 'http://someurl.com',
  COLOR: {
    ORANGE: '#C50',
    DARKBLUE: '#0F3274',
    LIGHTBLUE: '#6EA8DA',
    DARKGRAY: '#999',
  },
};

//使用...

import GLOBALS from '../Globals'; // the variable name is arbitrary since it's exported as default

//并以相同的方式访问它们之前

// and access them the same way as before

GLOBAL.COLOR.ORANGE