参考:
Blazor入门笔记(3)-C#与JS交互 - 半野 - 博客园
https://www.cnblogs.com/zxyao/p/12638233.html
Blazor项目如何调用js文件_blazor加载js-CSDN博客
https://blog.csdn.net/bdbox/article/details/135438411
本地环境:win10, visual studio 2022 community
其他例子写了再更新!
更新:调用单独的js文件
首先将js文件放到wwwroot下,然后修改函数,前面增加export关键字:
然后在用到这个函数的razor文件中,这样写:
@inject IJSRuntime JsRuntime<button @onclick="ExportSvg">Export SVG</button>
<svg id="mySvg"/>@code {private IJSObjectReference module;protected override async Task OnAfterRenderAsync(bool firstRender){if (firstRender){// 导入。路径是相对wwwroot写的,其他位置参考顶部链接module = await JsRuntime.InvokeAsync<IJSObjectReference>("import", "./exportSvg.js");}}private async Task ExportSvg(){var svgElement = await JsRuntime.InvokeAsync<IJSObjectReference>("document.getElementById", "mySvg");await module.InvokeVoidAsync("exportSvgToImage", svgElement, "png");}
}
调用js函数并传递参数
首先要加上@inject IJSRuntime JsRuntime
,在需要调用的地方写:
var name = "world";
var a = 11;
var b = 22;
var element = await JsRuntime.InvokeAsync<string>("interop.runJs", name, a, b);
其中runJs是函数的名称,后面是参数列表。element将得到返回值。再看runJs:
<script>window.interop = {runJs: (name, a, b) => {console.warn("runJs is executing");console.warn("hello " + name);return "OK " + (a + b);}}
</script>
绘制一个半径可随窗口大小变化的圆形
@page "/"@inject IJSRuntime JsRuntime<PageTitle>Index</PageTitle><svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><circle id="circle" cx="50" cy="50" r="@radius" fill="blue" />
</svg>@code {private double radius = 20;protected override async Task OnAfterRenderAsync(bool firstRender){if (firstRender){await UpdateCircleRadius();}}async Task UpdateCircleRadius(){var element = await JsRuntime.InvokeAsync<IJSObjectReference>("document.getElementById", "circle");var width = await element.InvokeAsync<int>("getBoundingClientRect").ConfigureAwait(false);radius = width / 10;}
}