问题
How do I set focus to a textbox in Blazor? So far the only way we have found is with JavaScript.
回答1:
There is no other way to do it... You can use JSInterop to do this, as follows:
<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);
}
}
}
JavaScript
<script>
window.exampleJsFunctions =
{
focusElement: function (element) {
element.focus();
}
};
</script>
Hope this helps...
回答2:
.Net 5 make this easy!
<input type="text" @ref="myref"/>
@code {
private ElementReference myref;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await myref.FocusAsync();
}
}
}
来源:https://stackoverflow.com/questions/60309188/how-do-i-set-focus-to-a-text-box-in-blazor