我想创建自定义输入,因此创建了以下组件:
MyInputComponent.razor:
<div>
<input type="text" @bind="BindingValue" />
</div>
@code {
[Parameter]
public string BindingValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后的用法:
<EditForm Model="model" OnValidSubmit="Submit">
<MyInputComponent BindingValue="model.Name" />
</EditForm>
@code {
User model = new User() { Name = "My Name" };
private void Submit()
{
// here I found model.Name = null;
}
}
Run Code Online (Sandbox Code Playgroud)
调试时MyInputComponent,我发现了输入的值。但是当我提交表单时,该值为null。
怎么做 ?
Maj*_*jor 10
一般来说,接受的答案是正确的并且工作正常。唯一需要添加的是代码示例使用基于事件的默认名称约定,例如:{PropertyName}Changed。
[Parameter] public EventCallback<string> BindingValueChanged { get; set; }
但是您可以覆盖此命名约定 @bind-{Property}:event="{EventCallbackName}"
<MyInputComponent @bind-BindingValue="model.Name" @bind-BindingValue:event="OnValueChanged"/>
.....
[Parameter] public EventCallback<string> OnValueChanged { get; set; }
Run Code Online (Sandbox Code Playgroud)
将 Blazor 与 .NET7 结合使用,您可以执行以下操作:
MyCustomComponent.Razor
<input type="text" @bind:get="BindingValue" @bind:set="SetAsync">
@code {
[Parameter]
public string BindingValue { get; set; }
[Parameter]
public EventCallback<string> BindingValueChanged { get; set; }
async Task SetAsync(string value)=> await BindingValueChanged.InvokeAsync(value);
}
Run Code Online (Sandbox Code Playgroud)
}
然后你可以使用:
<MyCustomComponent @bind-BindingValue="whateverVariable" />
Run Code Online (Sandbox Code Playgroud)
引用Blazor文档:
组件参数
绑定识别组件参数,其中@ bind- {property}可以跨组件绑定属性值。
对于您的页面:
<EditForm Model="model" OnValidSubmit="Submit">
<MyInputComponent @bind-BindingValue="model.Name" />
</EditForm>
Run Code Online (Sandbox Code Playgroud)
子组件MyInputComponent:
<div>
<InputText type="text" @bind-Value="@BindingValue" />
</div>
@code {
private string _value;
[Parameter]
public string BindingValue
{
get => _value;
set
{
if (_value == value ) return;
_value = value;
BindingValueChanged.InvokeAsync(value);
}
}
[Parameter]
public EventCallback<string> BindingValueChanged { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
请注意,您应该从子组件引发绑定更改EventCallback<string> BindingValueChanged。
| 归档时间: |
|
| 查看次数: |
352 次 |
| 最近记录: |