参考:
Blazor入门笔记(3)-C#与JS交互 - 半野 - 博客园
https://www.cnblogs.com/zxyao/p/12638233.html
本地环境:win10, visual studio 2022 community
其他例子写了再更新!
调用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;
}
}