【发布时间】:2020-06-04 03:27:47
【问题描述】:
如何在 Blazor 中将焦点设置到文本框?到目前为止,我们发现的唯一方法是使用 JavaScript。
【问题讨论】:
如何在 Blazor 中将焦点设置到文本框?到目前为止,我们发现的唯一方法是使用 JavaScript。
【问题讨论】:
.Net 5(或更高版本)让这一切变得简单!
<input type="text" @ref="myref"/>
@code {
private ElementReference myref;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await myref.FocusAsync();
}
}
}
【讨论】:
没有别的办法了……可以用JSInterop来做,如下:
<input type="text" @ref="myref"/>
@code {
private ElementReference myref;
[Inject] IJSRuntime JSRuntime { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await
JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", myref);
}
}
}
<script>
window.exampleJsFunctions =
{
focusElement: function (element) {
element.focus();
}
};
</script>
希望这会有所帮助...
【讨论】: