2016-08-19 76 views
13

如何創建常量文件,如:關鍵 - 在ReactJs值,陣營創建常量文件

ACTION_INVALID = "This action is invalid!" 

,並使用其他組件

errorMsg = myConstClass.ACTION_INVALID; 
+0

一全局常量?你是捆綁嗎? –

+0

我使用瀏覽器同步服務器 – TeodorKolev

回答

18

您可以簡單地創建爲您的常量的對象:

const myConstClass = { 
    ACTION_INVALID: "This action is invalid!" 
} 

然後使用它。

如果你是捆綁的,你可以將export這個對象,然後import爲每個組件文件。

+0

不起作用,什麼意思是捆綁? – TeodorKolev

21

我不能完全肯定我得到了你的問題,但如果我做到了,應該是很簡單的:

從我的理解,你只是想創建一個常量的文件,並在另一個文件中使用它。

fileWithConstants.js:

export const ACTION_INVALID = "This action is invalid!" 
export const CONSTANT_NUMBER_1 = 'hello I am a constant'; 
export const CONSTANT_NUMBER_2 = 'hello I am also a constant'; 

fileThatUsesConstants.js:

import * as myConstClass from 'path/to/fileWithConstants'; 

const errorMsg = myConstClass.ACTION_INVALID; 

如果您正在使用的反應,你應該有任何的WebPack或打包(用於反應母語),所以你應該有這通天可以將您使用的輸出和輸入轉換爲較老的js。

+0

導出常量無效 – TeodorKolev

+0

你是什麼意思?我假設你使用老版本的js,在這種情況下嘗試exports.ACTION_INVALID而不是導出const並使用require('path/to/fileWithConstants')。ACTION_INVALID而不是導入。 –

+0

'''events.js:160 throw er; //未處理'錯誤'事件 ^ SyntaxError:D:/constants.jsx:意外標記(2:11) 類常量擴展了React.Component { export const ACTION_INVALID =「此操作無效! export const CONSTANT_NUMBER_1 ='你好,我是一個常量'; export const CONSTANT_NUMBER_2 ='你好,我也是一個常量'; }''' – TeodorKolev

3

做到這一點的一種方法(與其他答案雖然沒有太大不同),但要創建一個裸constants.js文件並在其中添加常量。我用這個CONFIGS

module.exports = Object.freeze({ 
    ACTION_INVALID :'This action is invalid', 
    ACTION_VALID:'Some other action', 
}); 

然後,你可以要求它在任何地方

import ConstantsList from './constants'; 

,並使用

console.log(ConstantsList.ACTION_INVALID) 
2

擴展在Monad's answer,對於有些情況下,你不想鍵入myConstClass所有時間:

fileWithConstants.js:

export const ACTION_INVALID = "This action is invalid!" 
export const CONSTANT_NUMBER_1 = 'hello I am a constant'; 
export const CONSTANT_NUMBER_2 = 'hello I am also a constant'; 

fileThatUsesConstants.js:

import { ACTION_INVALID } from 'path/to/fileWithConstants'; 

const errorMsg = ACTION_INVALID; 

(另外,如果單子的方式爲你工作好,我相信公約是「MyConstClass」開始一個大寫字母,因爲它的作用就像一個在代碼類。)

0

如果你不想導入一切,你使用網絡。您可以創建一個文件,其名稱取決於您,但我會將其稱爲constants.js

//constants.js 
var MyConstants = { 
    apiUrl: "http://localhost/side-project/english/backend/" 
} 

在你index.html你可以叫constants.js以上的bundle.js

我使用的WebPack

This guy here 
<script type="text/javascript" src="/src/js/constants.js"></script> 
<script type="text/javascript" src="/dist/js/bundle.js"></script> 

而現在,你不會需要把import Constants from '..path_to_constants'在每一個文件