How do I set focus to a text box in Blazor

a 夏天 提交于 2020-12-12 04:03:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!