我正试图在Blazor中创建一个具有双向数据绑定的单选按钮组件,但我似乎无法更改父级上的值(testNumber(。我是Blazor和C#的新手,所以任何帮助都将不胜感激。感谢
ChildComp.剃须刀
<div>
<label for="radio1">1</label>
<input
id="radio1"
type="radio"
value="1"
name="test"
checked="@(_selectedGroup == 1)"
@onclick="@(() => _selectedGroup = 1)"/>
<label for="radio2">2</label>
<input
id="radio2"
type="radio"
value="2"
name="test"
checked="@(_selectedGroup == 2)"
@onclick="@(() => _selectedGroup = 2)"/>
</div>
@code {
private int _selectedGroup = 0;
[Parameter]
public int BindingValue
{
get => _selectedGroup;
set
{
if (_selectedGroup == value )
{
return;
}
else
{
_selectedGroup = value;
}
BindingValueChanged.InvokeAsync(value);
}
}
[Parameter]
public EventCallback<int> BindingValueChanged { get; set; }
}
ParentComp.剃须刀
<div>
<ChildComp @bind-BindingValue="testNumber" />
<h5>@testNumber</h5>
</div>
@code {
int testNumber = 0;
}
正如您可能注意到的,bind
不适用于单选按钮。在GitHub上,你可以在这里看到关于它的讨论。很遗憾Blazor不支持这些简单的功能。。。
我遇到了同样的问题,遇到了这个解决方案:
@code {
public int EditionCode = 1;
// "Edition" class has "int Code" and "string Text" properties.
public Edition[] Editions = new [] {
new Edition { Code = 1, Text = "Home" },
new Edition { Code = 2, Text = "Pro" },
new Edition { Code = 3, Text = "Enterprise" },
};
}
@foreach (var edition in this.Editions)
{
<label>
<input type="radio"
name="edition"
checked="@(EditionCode == edition.Code)"
onchange="@(() => EditionCode = edition.Code)"/>
@edition.Text
</label>
}
如果此解决方案不能解决您的需求,请查看此处(稍微复杂一点(。