在 Blazor 上按下输入键时更改变量值

Ven*_*sky 15 c# asp.net-core blazor

我想要做的是当用户按下一个键时更新变量值,但它只更新输入模糊时的值。

以下代码不起作用。

<p>@increment</p>
<input 
    type="text"
    @onchange="@((ChangeEventArgs e) =>
        increment = e.Value.ToString())"
/>

@code {
    string increment;
}
Run Code Online (Sandbox Code Playgroud)

使用@bind@bind-value也不起作用。

我用这个例子做了一个blazorfiddle

当按下 a 键时,谁能改变我的变量的值?

dan*_*era 34

回答:

引用数据绑定文档:

<input @bind="CurrentValue" 
       @bind:event="oninput" />
Run Code Online (Sandbox Code Playgroud)

onchange当元素失去焦点时触发的不同,当oninput文本框的值改变时触发。

使用@oninput:

您可以在没有@bind指令的情况下实现它:

<input value="@CurrentValue"
       @oninput="(e)=> CurrentValue = e.Value.ToString()"/>
Run Code Online (Sandbox Code Playgroud)

InputText & oninput

对于oninputInputText组件上寻找答案的人,基于输入事件文档的InputText完整记录了答案:

使用 InputText 组件创建使用输入事件而不是更改事件的自定义组件。Shared/CustomInputText.razor

@inherits InputText

<input @attributes="AdditionalAttributes" class="@CssClass" 
    @bind="CurrentValueAsString" @bind:event="oninput" />
Run Code Online (Sandbox Code Playgroud)

CustomInputText组件可以在任何使用的地方InputText使用:

<CustomInputText @bind-Value="exampleModel.Name" />
Run Code Online (Sandbox Code Playgroud)

  • 如果您不使用组件(例如“InputText”),表单验证将停止工作。看起来要么我失去了验证,要么如果我保持验证,我就失去了更新绑定的能力。 (2认同)