【问题标题】:How to set focus on Blazor.Typeahead component?如何将焦点设置在 Blazor.Typeahead 组件上?
【发布时间】:2020-11-07 20:57:54
【问题描述】:

我在我的项目中使用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 文件的标题中有这个脚本。

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

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

错误 CS0029 无法隐式转换类型 'Blazored.Typeahead.BlazoredTypeahead' 到 'Microsoft.AspNetCore.Components.ElementReference'

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

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常渲染组件:派生类必须实现它 System.NotImplementedException:派生类必须 实现它

【问题讨论】:

    标签: asp.net-core focus blazor typeahead.js blazor-client-side


    【解决方案1】:

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

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

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

    【讨论】:

    • 我没有在 html 源代码中看到 ID 标记,但我看到了一个类名,所以我使用了 JavaScript 的 getElementsByClassName 并以这种方式设置焦点。谢谢!
    最近更新 更多