Global Variable / Constant in React Native

后端 未结 4 1293
北荒
北荒 2021-02-01 02:03

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 al

相关标签:
4条回答
  • 2021-02-01 02:24

    I too made a module like in Chris Geirman's answer, but was not able to reference it with the require. Instead I got it to work with import * as GLOBAL from '../Globals';

    0 讨论(0)
  • 2021-02-01 02:25

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

    // 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
    

    _____________________

    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.

    ECMAScript Modules (ESM) Syntax

    // File: Globals.js

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

    // to use...

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

    // and access them the same way as before

    GLOBALS.COLOR.ORANGE
    
    0 讨论(0)
  • 2021-02-01 02:43

    global in react native is like the window in web development.

    // declare a global varible
    global.primaryColor = '***';
    
    //now you can use this variable anywhere
    console.log(primaryColor);
    
    0 讨论(0)
  • 2021-02-01 02:48

    If you want to switch between languages depening on platform localisation.

    fetch node_module via npm

    npm i react-native-localization --save 
    

    Define variables in class:

    // Localisation.js
    let LocalizedStrings = require ('react-native-localization'); 
    let strings = new LocalizedStrings ({ 
     en: { 
         loginTitle:  "Login",
     }, 
     de: {
         loginTitle:  "Anmelden",
     }
    })
    

    When you need the strings:

    var STRINGS = require ('./Localization');
    <Text>{STRINGS.loginTitle}</Text>
    
    0 讨论(0)
提交回复
热议问题