React中constants.js文件内无法引用同文件导出常量的问题
问题分析与解决
你现在的代码里,myObject里的myConstant1和myConstant2是对象的键名,不是对外部常量的引用。在JavaScript对象字面量中,直接写标识符会被当作字符串键处理,所以这里的键只是字符串"myConstant1",和外部定义的myConstant1变量完全无关,自然不会识别到外部的常量。
根据你的需求,分两种场景解决:
场景1:用外部常量作为对象的键名
如果想让对象的键是myConstant1和myConstant2的值(也就是'abc'和'xyz'),需要用ES6的计算属性名语法,把变量放在方括号里:
export const myConstant1 = 'abc'; export const myConstant2 = 'xyz'; export const myObject = { [myConstant1]: 'This is the first constant', [myConstant2]: 'This is the second constant' }
此时myObject的结构是:
{ abc: 'This is the first constant', xyz: 'This is the second constant' }
场景2:把外部常量的值作为对象属性的值
如果想让myObject的myConstant1属性值等于外部的myConstant1变量值(也就是'abc'),直接把变量名写在赋值位置即可,还可以用ES6的属性简写(键名和变量名一致时):
export const myConstant1 = 'abc'; export const myConstant2 = 'xyz'; // 完整写法 export const myObject = { myConstant1: myConstant1, myConstant2: myConstant2 } // ES6简写(推荐) export const myObject = { myConstant1, myConstant2 }
此时myObject的结构是:
{ myConstant1: 'abc', myConstant2: 'xyz' }
内容的提问来源于stack exchange,提问作者Greeso
相关产品推荐
相关产品推荐

