使用 ES6 静态函数时,我得到“没有这样的方法”

2024-05-10

我正在尝试为我在 React Native 中工作的项目创建一个包含静态函数的“utils”类。

我读到了如何在 StackOverFlow 中创建静态函数question https://stackoverflow.com/questions/29893591/es6-modules-export-single-class-of-static-methods-or-multiple-individual-method%20question,但由于某种奇怪的原因,它对我不起作用。

//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>");

但我不断收到此错误“Utils.textFormat 不是函数”,我做错了什么?


好事你让事情正常工作,但我只想添加一个更接近你最初想要做的解决方案,并注意中提出的观点你链接的SO问题 https://stackoverflow.com/questions/29893591/es6-modules-export-single-class-of-static-methods-or-multiple-individual-method%20question.

只是没有必要使用class导出一堆静态方法。我不知道它将如何增加代码的功能、易用性或清晰度。实际上恰恰相反,语法看起来比导出普通的旧 ES5 样式对象更冗长,当我们将 ES6+ 的优点融入其中时更是如此。


您的 utils 模块的原始示例工作得很好。问题在于import.

由于您只是导出一个默认对象,因此导入它的正确方法是

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>");

Or像这样

import {textFormat} from './utils/utils';

var text = textFormat(rowData.text, "<Text style={{color:'blue'}}>Hey there</Text>");

无论你喜欢哪个。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ES6 静态函数时,我得到“没有这样的方法” 的相关文章

随机推荐