Syd*_*ria 36 android ios reactjs react-native
在React Native中有一种方法可以在全局变量上定义我将使用的所有字符串,就像在Android开发中一样,有一个String.xml,您可以在其中放置所有字符串.
Chr*_*man 113
我做的是创建一个全局模块......
//文件:Globals.js
module.exports = {
STORE_KEY: 'a56z0fzrNpl^2',
BASE_URL: 'http://someurl.com',
COLOR: {
ORANGE: '#C50',
DARKBLUE: '#0F3274',
LIGHTBLUE: '#6EA8DA',
DARKGRAY: '#999',
},
};
Run Code Online (Sandbox Code Playgroud)
然后我只需要顶部...
const GLOBAL = require('../Globals');
Run Code Online (Sandbox Code Playgroud)
并像这样访问它们......
GLOBAL.COLOR.ORANGE
Run Code Online (Sandbox Code Playgroud)
这似乎是一个非常流行和有用的答案,所以我认为我应该用更新的语法更新它.上述内容仍然可以在CommonJS模块系统中运行,但现在您可能会遇到ES6和import
模块而不是require
它们.
//文件:Globals.js
export default {
STORE_KEY: 'a56z0fzrNpl^2',
BASE_URL: 'http://someurl.com',
COLOR: {
ORANGE: '#C50',
DARKBLUE: '#0F3274',
LIGHTBLUE: '#6EA8DA',
DARKGRAY: '#999',
},
};
Run Code Online (Sandbox Code Playgroud)
//使用......
import GLOBALS from '../Globals'; // the variable name is arbitrary since it's exported as default
Run Code Online (Sandbox Code Playgroud)
//并以与以前相同的方式访问它们
GLOBALS.COLOR.ORANGE
Run Code Online (Sandbox Code Playgroud)
小智 40
global
反应本机就像Web开发中的窗口.
// declare a global varible
global.primaryColor = '***';
//now you can use this variable anywhere
console.log(primaryColor);
Run Code Online (Sandbox Code Playgroud)
Ver*_*rsa 10
我也在Chris Geirman的答案中制作了一个模块,但是无法用require来引用它.相反,我得到了它import * as GLOBAL from '../Globals';
如果要在依赖于平台本地化的语言之间切换.
通过npm获取node_module
npm i react-native-localization --save
Run Code Online (Sandbox Code Playgroud)
在类中定义变量:
// Localisation.js
let LocalizedStrings = require ('react-native-localization');
let strings = new LocalizedStrings ({
en: {
loginTitle: "Login",
},
de: {
loginTitle: "Anmelden",
}
})
Run Code Online (Sandbox Code Playgroud)
当你需要字符串时:
var STRINGS = require ('./Localization');
<Text>{STRINGS.loginTitle}</Text>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
43667 次 |
最近记录: |