本文介绍了如何在自定义组件Blazor上使用bind-value和bind-value:event的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Blazor中,使用输入时,

In Blazor, while using inputs,

<input bind-value="@InputValue" bind-value:event="oninput"/>

这将创建一种双向绑定,该绑定会随着oninput事件更新.

This creates a 2 way binding that updates with the oninput event.

我想在具有自定义事件和自定义属性的自定义组件上重新创建它.

I would like to recreate this on a custom component with custom events and custom properties.

CustomInput.razor

<input value="@Value" oninput="@OnInput" />

@code {
   [Parameter]
   public string Value { get; set; }

   [Parameter]
   public EventCallback<ChangeEventArgs> OnInput { get; set; }
}

我希望能够以这种方式使用它.

I want to be able to use it this way.

<CustomInput bind-Value="@InputValue" bind-Value:event="OnInput" />

现在在Blazor上有可能吗?如果是,我该如何实现?

Is this possible on Blazor right now? If yes, how do I achieve it?

对于遇到此问题的任何人,它似乎都可以正常工作.我不确定在提出问题后是否添加了该功能,或者它是否始终可以这种方式运行,但是上面的代码应该按原样运行.按照惯例,您的事件名称应为 ValueChanged ,但是如果您有理由使用其他事件名称,例如在具有 OnInput OnChange 的输入中,那么您可以使用这种格式.

For anyone that comes across this, it seems to work as is. I am not sure if the feature was added after the question was asked or if it always worked that way but the code above should work as is. Conventionally, your event name should be ValueChanged but if you have a reason to use another event name like in inputs where you have OnInput and OnChange, then you can use this format.

推荐答案

是的Blazor支持2种方式的绑定.它与EventCallbacks(必须触发)一起使用,并且默认使用基于名称约定的事件,例如: {PropertyName} Changed .您也可以覆盖此命名约定 @ bind- {Prop}:event =" {EventCallbackName}" .在您的代码示例中,您只是覆盖了此默认事件名称,而从未触发过它.

Yes Blazor supports 2 way binding. It works with EventCallbacks (which must be triggered) and default uses name convention based Events e.g.: {PropertyName}Changed. Also you can override this naming convention @bind-{Prop}:event="{EventCallbackName}". In your code example you are just overriding this default Event name, never triggering it.

在您的代码中有两个问题:

  1. 您必须定义以 @ 开头并在"" 内的绑定,没有必要使用 @ 正确,其为: @ bind- {PropertyName} =""{variable}"" .
  1. You MUST define bind starting with @ and inside "" it is not necessary to use @ correct for is: @bind-{PropertyName}="{variable}".

将您的代码更改为:< CustomInput @ bind-Value =" InputValue"@ bind-Value:event =" OnInput"/>

  1. 已经写道,必须在实际值更改时触发这些事件.将您的代码更新为:
private string _value;
[Parameter] public string Value 
{ 
   get => _value; 
   set
   {
      if(value == _value)
        return;

      _value = value;  
      if(OnInput.HasDelegate)
      {
         OnInput.InvokeAsync(_value);
      }  
   }
}

这篇关于如何在自定义组件Blazor上使用bind-value和bind-value:event的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 17:03