当我在'formset'中创建新表单时,我想聚焦新表单。
使用此代码,我得到了所需的结果,但是我得到"发生了未处理的错误。重新加载"和控制台中的以下错误:
控制台中的错误
非常感谢!
<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);
}
网站.js:
function setFocusOnElement(element) {
element.focus();
}
尽管有错误消息,但我相信这与渲染的时间有关......调用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>