我是 .NetCore Blazor
的新手,正在尝试将 ExampleJsInterop JavaScript
代码转换为 TypeScript
。
我在转换以下代码时遇到问题:
window.exampleJsFunctions = {
showPrompt: function (text) {
return prompt(text, 'Type your name here');
},
displayWelcome: function (welcomeMessage) {
document.getElementById('welcome').innerText = welcomeMessage;
},
returnArrayAsyncJs: function () {
DotNet.invokeMethodAsync('BlazorSample', 'ReturnArrayAsync')
.then(data => {
data.push(4);
console.log(data);
});
},
sayHello: function (dotnetHelper) {
return dotnetHelper.invokeMethodAsync('SayHello')
.then(r => console.log(r));
}
};
当然,转换前两个函数和最后一个函数没有问题,但是我无法转换第三个函数,因为 DotNet
在 TypeScript 上无效:
returnArrayAsyncJs: function () {
DotNet.invokeMethodAsync('BlazorSample', 'ReturnArrayAsync')
.then(data => {
data.push(4);
console.log(data);
});
}
我的问题首先是,如何将这个JS
函数转换为TS
。如果有人帮助我了解此 DotNet
的来源,那也会很有帮助。
提前致谢。
最佳答案
where this DotNet comes from
一般来说,DotNet
来自 JSInterop/Microsoft.JSInterop.JS
单个文件(参见 Source Code on GitHub )。此文件导入到 blazor.server.js
中.你会引用这个 blazor.server.js
在你的脚本 Pages/_Host.csthml
:
<body>
<app>
@(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))
</app>
<script src="_framework/blazor.server.js"></script>
<script src="/built/exampleJsInterop.js" ></script>
</body>
</html>
当 blazor.server.js
在运行时加载,全局 DotNet
已创建。
您可以搜索字符串 window.DotNet=
在blazor.server.js
确认。自 DotNet
作为 window
的属性附加, 它成为您浏览器中的全局变量。
how can I convert this JS function to TS.
微软尚未发布官方.d.ts
Microsoft.JsInterop
的包裹图书馆。参见 https://github.com/aspnet/Blazor/issues/1452
有一个 https://www.npmjs.com/package/@dotnet/jsinterop
在 npmjs.com 上。但要小心,因为它似乎不是官方版本(不确定)。
一种安全的方式,如 @SteveSandersonMS in above links 所建议的那样, 是生成 d.ts
由我们自己:
- 复制文件并保存为
Microsoft.JsInterop.ts
: https://github.com/aspnet/Extensions/blob/master/src/JSInterop/Microsoft.JSInterop.JS/src/src/Microsoft.JSInterop.ts - 运行
tsc --declaration
并得到Microsoft.JsInterop.d.ts
文件,保存在路径wwwroot/@types/Microsoft.JsInterop.d.ts
. 在您的
exampleJsInterop.ts
内文件,假设它的路径是wwwroot/ts/exampleJsInterop.ts
, 只需添加声明引用/// <reference types="../@types/Microsoft.JsInterop" />
在第一行:└───wwwroot/ ├───@types/ | |─── Microsoft.JsInterop.d.ts ├───built/ └───ts/ |─── exampleJsInterop.ts
现在您可以享受
DotNet
中的 typescript 功能模块。见智能感知:对了,我也改了
data => {data.push(4);... }
至(data: Number[])=> {... }
关于javascript - 将 JSInterop 的 ExampleJsInterop JavaScript 代码转换为 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58419012/