Blazor结合MudBlazor实现表单回车键自动跳转及提交功能
Blazor MudBlazor 注册表单回车自动跳转实现方案
前置修改:补充输入框引用
首先给每个MudTextField添加@ref标识,方便后续调用聚焦方法,修改后的输入框代码如下:
<MudCardContent> <MudTextField @ref="_usernameRef" Label="First name" HelperText="Max. 8 characters" @bind-Value="model.Username" For="@(() => model.Username)" @onkeydown="async (e) => await Keydown(e)"/> <MudTextField @ref="_emailRef" Label="Email" Class="mt-3" @bind-Value="model.Email" For="@(() => model.Email)" @onkeydown="async (e) => await Keydown(e)"/> <MudTextField @ref="_passwordRef" Label="Password" HelperText="Choose a strong password" Class="mt-3" @bind-Value="model.Password" For="@(() => model.Password)" InputType="InputType.Password" @onkeydown="async (e) => await Keydown(e)"/> <MudTextField @ref="_password2Ref" Label="Password" HelperText="Repeat the password" Class="mt-3" @bind-Value="model.Password2" For="@(() => model.Password2)" InputType="InputType.Password" @onkeydown="async (e) => await Keydown(e)"/> </MudCardContent>
完善@code块逻辑
在原有代码基础上补充输入框引用定义,重写Keydown方法即可:
// 新增:输入框引用定义 private MudTextField<string> _usernameRef; private MudTextField<string> _emailRef; private MudTextField<string> _passwordRef; private MudTextField<string> _password2Ref; // 修改后的Keydown方法 public async Task Keydown(KeyboardEventArgs e) { // 仅处理回车键事件 if (e.Key != "Enter") return; // 按表单输入顺序整理输入框与对应值的映射 var inputSequence = new List<(MudTextField<string> Input, string FieldValue)> { (_usernameRef, model.Username), (_emailRef, model.Email), (_passwordRef, model.Password), (_password2Ref, model.Password2) }; // 定位当前触发事件的输入框位置 var currentIndex = inputSequence.FindIndex(item => item.Input.ElementReference.Id == (e.Target as ElementReference?).Value.Id); if (currentIndex < 0) return; // 向后查找第一个未填充的输入框,找到后直接聚焦 for (int i = currentIndex + 1; i < inputSequence.Count; i++) { if (string.IsNullOrWhiteSpace(inputSequence[i].FieldValue)) { await inputSequence[i].Input.FocusAsync(); return; } } // 所有字段已填充,触发校验与提交 var editContext = new EditContext(model); if (editContext.Validate()) { OnValidSubmit(editContext); } }
逻辑说明
- 仅拦截回车键事件,不影响其他正常输入操作
- 按照表单输入顺序向后遍历,跳过已填充字段,自动聚焦到第一个空字段
- 遍历结束没有空字段时,自动触发表单校验,校验通过执行原有提交逻辑
内容的提问来源于stack exchange,提问作者buddhi chamalka
相关产品推荐
相关产品推荐

