如何将焦点设置为InputText元素? [英] How to set the focus to an InputText element?

查看:62
本文介绍了如何将焦点设置为InputText元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用

Using the example from the Microsoft docs, I'm trying to programmatically set the focus to an input element.

不幸的是,该示例使用标准的< input type ="text"> ,而我想将其用于

Unfortunately, the example uses a standard <input type="text"> whereas I want to use it for an InputText element.

Microsoft示例使用扩展方法,该方法采用 ElementReference :

The Microsoft example uses an extensions method that takes an ElementReference:

public static Task Focus(this ElementReference elementRef, IJSRuntime jsRuntime)
{
    return jsRuntime.InvokeAsync<object>(
        "exampleJsFunctions.focusElement", 
        elementRef);
}

使用 InputText ,我看不到获得这样的 ElementReference 的方法.

Using an InputText, I see no way of obtaining such an ElementReference.

使用 InputText 提供我自己的 Focus()重载,但已编译,但未显示任何视觉效果.因此,我一无所知.

Providing my own Focus() overload with an InputText instead, compiled but showed no visual result. Therefore I'm clueless.

如何通过编程将焦点设置为 InputText 元素?

How can I programmatically set the focus to an InputText element?

推荐答案

您可以将 id 参数添加到 InputText 并修改 Focus 方法和JavaScript代码.

You can add id parameter to your InputText and modify your Focus method and JavaScript code.

public async Task Focus(string elementId)
{
    await JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", elementId);
}

focusElement: function (id) {
    const element = document.getElementById(id); 
    element.focus();
}

注意:这不是一个适当的解决方案,而是更多解决方法,但Blazor似乎并不直接支持它.

Note: this is more a workaround than a proper solution, but Blazor doesn't seem to support it directly.

这篇关于如何将焦点设置为InputText元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆