javascript - 如何在 reactjs 组件中使用使用 scalajs 导出的函数?
问题描述
我尝试main.js
使用@JSExportTopLevel
注释将一些函数导出到 scalajs 中的文件,如Export Scala.js APIs to JavaScript scalajs 文档中所述,并main.js
按照此处所述构建。
这导致main.js
我可以使用在 scalajs 代码中导出的函数。
现在我想在我的 reactjs 组件中使用这些导出的函数。为此,我尝试了以下步骤:
- 复制
main.js
文件public
夹中的文件 - 在 中包含 javascript 文件
index.html
,如下所示:
<script type="text/javascript" src="./main.js"></script>
现在,如果我在浏览器中加载应用程序并尝试在浏览器控制台中使用这些功能,它可以正常工作:
console.log(foo());
但我不是在 reactjs 组件中使用这些功能:
import React from 'react';
const RuleEditor = () => {
console.log(foo());
return (
<>
</>
);
};
export default RuleEditor;
我总是收到以下编译错误:
foo is not defined no-undef
我确实理解 reactjs 无法识别该功能,因为我还没有真正指定从哪里获取该功能,但我不确定如何实现它。我已经看过其他几个 stackoverflow 帖子,其中一些建议在window
对象中查找它,但我没有在那里找到这些函数。
请提出一种正确的方法来使用从 scalajs 导出的函数在 reactjs 组件中。TIA。
解决方案
将对象/类/函数导出为顶级导出将它们置于 Javascript 全局范围内。
class Foo(val x: Int) {
@JSExport
def square(): Int = x*x // note the (), omitting them has a different behavior
@JSExport("foobar")
def add(y: Int): Int = x+y
}
您可以在嵌入在 html 或 scalajs 中的脚本中使用这些函数,如此处所示。
但是如果您需要在 nodejs 应用程序中使用这些功能,则需要从模块中导出这些功能。我们需要在build.sbt
. 在这里阅读更多。
scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.ESModule) }
现在,我们可以通过像这样导入它们来在 nodejs 应用程序中使用导出的函数:
import { square, add } from './main'
如果您希望从名为 以外的模块导出这些函数main
,请为每个导出的函数提供模块 ID,如下所示:
class Foo(val x: Int) {
@JSExport("square", "my-math")
def square(): Int = x*x // note the (), omitting them has a different behavior
@JSExport("foobar", "my-math")
def add(y: Int): Int = x+y
}
并像这样使用它:
import { square, add } from './my-math'
推荐阅读
- python - 有没有办法在 Django Rest Framework 中添加自定义字段
- c++ - 如何在系统杀死正在运行的线程之前从单独的模块中删除单例实例
- javascript - Angular:我必须从商店获取调度值,但无法获取
- amazon-web-services - aws 应用程序负载均衡器后面的服务的固定 IP 地址
- apache-kafka - 卡夫卡不会重新开始
- shell - awk 打印与特定最后一条记录关联的字段
- laravel - Laravel7:验证上传的文件
- ios - 有没有办法让当前未呈现的视图的第一响应者辞职?
- c# - .Net Framework:未捕获异常时未调用 finally 块
- jenkins - 是否可以组合或混合 Jenkins 声明式和脚本化管道?