如何将焦点设置在 Blazor.Typeahead 组件上?

How to set focus on Blazor.Typeahead component?

我在我的项目中使用 BlazorTypeahead 组件。我想将焦点放在预先输入的文本框上,但似乎不知道该怎么做。这是我的页面。搜索和值更改方法工作正常,所以我将它们排除在外。

@page "/"
@using Microsoft.JSInterop
@using Microsoft.AspNetCore.Components
@inject IJSRuntime jsRuntime
@inject Blazored.LocalStorage.ILocalStorageService localStore

<BlazoredTypeahead SearchMethod="SearchMyModel" TItem="MyModel" TValue="MyModel" Value="SelectedMyModel" ValueChanged="MyModelChanged" ValueExpression="@(() => SelectedMyModel)" placeholder="My Model name..." @ref="NewElementHere">
    <SelectedTemplate>
        @context.Name
    </SelectedTemplate>
    <ResultTemplate>
        @context.Name (@context.AnotherProperty)
    </ResultTemplate>
</BlazoredTypeahead>
    
    
@code {
    //public BlazoredTypeahead<MyModel, MyModel> NewElementHere { get; set; }
    ElementReference NewElementHere;
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // Focus the element
            await jsRuntime.InvokeAsync<object>("BlazorFocusElement", NewElementHere);
        }
    }
}

index.html 文件在 header 中有此脚本。

window.BlazorFocusElement = (element) => {
    if (element instanceof HTMLElement) {
        element.focus();
    }
};

上面的代码产生以下编译时错误:

Error CS0029 Cannot implicitly convert type 'Blazored.Typeahead.BlazoredTypeahead<MyModel, MyModel>' to 'Microsoft.AspNetCore.Components.ElementReference'

如果我删除 ElementReference 并启用 [即删除评论] @code 中的 属性,它会构建,但我收到运行时错误 发生了未处理的错误。 如果我查看 Web 调试器控制台,它会显示:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Derived classes must implement it System.NotImplementedException: Derived classes must implement it

您不能将 ElementReference 应用到组件... BlazoredTypeahead 是一个组件,所以您不能这样做。 BlazoredTypeahead 的作者应该已经提供了一种方法来做到这一点...查看此组件的方法和属性。也许此组件通过其属性之一提供此类功能...

无论如何,你不能在这里使用ElementReference。但我想你仍然可以使用 JSInterop 来设置焦点,即使你想要设置焦点的输入文本没有 id 属性。只需查看 Html 源代码,识别输入文本元素,并想出一种设置焦点的方法。

请注意,如果您使用的是 .Net 5.0,则可以从 Blazor 设置焦点。