如何将焦点设置到 Blazor 中的文本框

Noe*_*oel 20 blazor blazor-server-side

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

Ale*_*dre 40

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

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

@code {

    private ElementReference myref;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await myref.FocusAsync();
        }
   }
}
Run Code Online (Sandbox Code Playgroud)

  • FocusAsync 的许多示例都没有提到必须在 OnAfterRenderAsync 方法中调用它(如 Alexandre 所示)。另外不要错过 FocusAsync 有一个可选的 bool arg,可以将焦点元素滚动到视图中。 (2认同)

Nb7*_*777 6

如果您有一个像这样的内置类型InputNumber并且您正在使用.Net6,您可以应用 @Alexandre 的解决方案,但需要进行一些更改,如下所示:

<InputNumber @ref="MyRef" @bind-Value="MyValue" />
<button class="btn btn-primary" @onclick="MyClick"> Click me </button>

private InputNumber<int> MyRef;
private int MyValue {get; set;}

//Some click event
private void MyClick()
{
   if(MyRef.Element.HasValue) 
   {
     MyRef.Element.Value.FocusAsync();
   }
}
Run Code Online (Sandbox Code Playgroud)


Isa*_*aac 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);
        }
   }
 }
Run Code Online (Sandbox Code Playgroud)

JavaScript

<script>

    window.exampleJsFunctions =
    {
        focusElement: function (element) {
           element.focus();
        }
    };
</script>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助...