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)
如果您有一个像这样的内置类型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)
没有其他方法可以做到这一点...您可以使用 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)
<script>
window.exampleJsFunctions =
{
focusElement: function (element) {
element.focus();
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助...
| 归档时间: |
|
| 查看次数: |
14668 次 |
| 最近记录: |