【问题标题】:How to do two-way binding on a radio button Blazor child component如何在单选按钮 Blazor 子组件上进行双向绑定
【发布时间】:2021-03-23 21:37:04
【问题描述】:

我正在尝试在 Blazor 中创建一个具有两种数据绑定方式的单选按钮组件,但我似乎无法更改父级上的值 (testNumber)。我是 Blazor 和 C# 的新手,因此将不胜感激任何帮助。谢谢

ChildComp.razor

<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.razor

<div>
    <ChildComp @bind-BindingValue="testNumber" />
    <h5>@testNumber</h5> 
</div>

@code {

    int testNumber = 0;
}

【问题讨论】:

  • 我也有同样的问题。运气好吗?

标签: radio-button blazor parent-child blazor-webassembly two-way-binding


【解决方案1】:

您可能已经注意到bind 不适用于单选按钮。在 GitHub 上你可以看到关于它的讨论 here。很遗憾 Blazor 不支持这些简单的功能...

我遇到了同样的问题,遇到了这个solution

@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>
}

如果此解决方案不能满足您的需求,请查看here(有点复杂)。

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2021-03-18
    • 1970-01-01
    • 2019-10-01
    • 2016-04-10
    相关资源
    最近更新 更多