【问题标题】:How do I set focus to a text box in Blazor如何将焦点设置到 Blazor 中的文本框
【发布时间】:2020-06-04 03:27:47
【问题描述】:

如何在 Blazor 中将焦点设置到文本框?到目前为止,我们发现的唯一方法是使用 JavaScript。

【问题讨论】:

标签: blazor blazor-server-side


【解决方案1】:

.Net 5(或更高版本)让这一切变得简单!

<input type="text" @ref="myref"/>

@code {

    private ElementReference myref;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await myref.FocusAsync();
        }
   }
}

【讨论】:

    【解决方案2】:

    没有别的办法了……可以用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);
            }
       }
     }
    

    JavaScript

    <script>
    
        window.exampleJsFunctions =
        {
            focusElement: function (element) {
               element.focus();
            }
        };
    </script>
    

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多