【问题标题】:Blazor JSRuntime Focus on Element in foreach [duplicate]Blazor JSRuntime 关注 foreach 中的元素 [重复]
【发布时间】:2019-12-29 07:42:22
【问题描述】:

当我在“表单集”中创建新表单时,我想关注新表单。

使用此代码,我得到了想要的结果,但我得到一个“发生未处理的错误”。 Reload' 和控制台中的以下错误:

errors in console

非常感谢!

<EditForm Model="todos" OnValidSubmit="Save">
    <table>
        <thead>
            <tr>
                <th>TODO</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var todo in todos)
            {
                if (todos.IndexOf(todo) != todos.Count - 1)
                {
                    <tr>
                        <td><input @bind="@todo.Name" /></td>
                    </tr>
                }
                if (todos.IndexOf(todo) == todos.Count - 1)
                {
                    <tr>
                        <td><input @ref="element" @onkeydown="@((KeyboardEventArgs e) => Newline(e))" @bind="@todo.Name" /></td>
                    </tr>
                }
            }
        </tbody>
    </table>
    <button class="btn btn-success" type="submit">Save</button>
</EditForm>

在我的代码块中:

ElementReference element;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
     await JSRuntime.InvokeVoidAsync("setFocusOnElement", element);
}

site.js:

function setFocusOnElement(element) {
    element.focus();
}

【问题讨论】:

    标签: blazor


    【解决方案1】:

    尽管有错误消息,但我相信这与渲染的时间有关......像这样调用 InvokeVoidAsync:

    ElementReference element;
    
     protected override async Task OnAfterRenderAsync(bool firstRender)
     {
            if (firstRender)
            {
                await JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", element);
             }
         }
    

    _Host.cshtml:

    <script src="_framework/blazor.server.js"></script>
    <script>
    
        window.exampleJsFunctions =
        {
            focusElement: function (element) {
               element.focus();
            }
        };
    </script>
    

    【讨论】:

    • if(!firstRender) 成功了。谢谢!
    • 你能更新你的答案以便我接受吗?
    猜你喜欢
    • 2020-12-23
    • 2020-09-28
    • 2021-11-06
    • 2021-01-21
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2020-12-20
    相关资源
    最近更新 更多