我正在尝试创建一个带有静态函数的“utils”类,用于我在本机中工作的项目.
我读到了如何在StackOverFlow question中创建静态函数,但由于某些奇怪的原因,它对我不起作用.
//utils.js 'use strict' export default { textFormat(args) { var s = args[0]; for (var i = 0; i < args.length - 1; i++) { var reg = new RegExp("\\{" + i + "\\}","gm"); s = s.replace(reg,args[i + 1]); } return s; } } //main file import * as Utils from './utils/utils'; /** /... **/ var text = Utils.textFormat(rowData.text,"<Text style={{color:'blue'}}>Hey there</Text>");
解决方法
让事情有效的好事,但我只是想添加一个更接近你原本想做的解决方案,并注意
the SO question you linked中的观点.
没有必要使用类来导出一堆静态方法.我不知道它将如何为代码添加功能,易用性或清晰度.实际上相反,语法看起来比导出简单的旧ES5样式对象更加冗长,当我们将ES6的甜味带入混合时更是如此.
您的utils模块的原始示例工作得很好.问题在于导入.
由于您只是导出一个默认对象,因此导入它的正确方法是
import Utils from './utils/utils';
没有括号,没有星号,只是导入的默认对象的名称,然后可以像var text = Utils.textFormat(…)一样使用.
不过,我们可以走得更远.通过抛弃整个“导出一个默认对象”的方法,我们可以使用模块系统的全部功能.
utils.js:
'use strict' function textFormat(args) { var s = args[0]; ... return s; } const someOtherUtility = str => str + ' works!'; export { textFormat,someOtherUtility };
现在可以像这样使用导出的函数
import * as Utils from './utils/utils'; var text = Utils.textFormat(rowData.text,"<Text style={{color:'blue'}}>Hey there</Text>");
或者像这样
import {textFormat} from './utils/utils'; var text = textFormat(rowData.text,"<Text style={{color:'blue'}}>Hey there</Text>");
无论你喜欢什么.