React Native中的全局变量/常量 [英] Global Variable / Constant in React Native

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

问题描述

在React Native中是否有一种方法可以在全局变量上定义我将使用的所有字符串,就像在Android开发中一样,有一个String.xml,您可以在其中放置所有字符串。

is there a way in React Native that I can define on a global variable all the strings that I will be using like in Android Development there is a String.xml where you can put all of your strings.

推荐答案

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

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

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

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