blazor 复制文字到剪贴板
3.与JS的互操作
上面实现了GUID天生器,然则每次天生了都需要自己去输入框复制,不方便,现在实现一个自动复制到剪贴板的功效。
此功效无法百分百通过C#代码来实现,需要与JS举行交互。
先编写 JS:
window.clipboardCopy = {
copyText: function (text) {
navigator.clipboard.writeText(text).then(function () {
alert("Copied to clipboard!");
})
.catch(function (error) {
alert(error);
});
}
};
该JS放置的位置,可以写在Js文件中,在Index.html中应用,也可以直接写在 Index.html中。
然后在 Razor 组件中注入 JSRuntime,并挪用该JS:
@page "/counter"
@inject IJSRuntime JsRuntime
<h1>GUID 天生器</h1>
<div class="row">
<div class="col-2">
<input class="form-control" type="text" value="@_guidValue" />
</div>
<div class="col-10">
<button class="btn btn-primary" @onclick="GenerateGuid">生 成</button>
<button class="btn btn-danger" @onclick="CopyTextToClipboard">复制到剪贴板</button>
</div>
</div>
@code {
private Guid? _guidValue;
private void GenerateGuid()
{
_guidValue = Guid.NewGuid();
}
private async Task CopyTextToClipboard()
{
await JsRuntime.InvokeVoidAsync("clipboardCopy.copyText", _guidValue);
}
}
运行:
小技巧:通过 dotnet watch run
下令可以获得更快乐的开发体验。