【问题标题】:binding button to child component blazor将按钮绑定到子组件 blazor
【发布时间】:2021-03-18 07:23:56
【问题描述】:

这是我的小提琴https://blazorfiddle.com/s/d15hrars

我有一个选择组件可以更改表的类。还有一个按钮可以设置选择组件的选择值。但按下按钮不会更新下拉列表中的选定值(选择组件)

因此按下按钮会突出显示 San Jose 行,但不会更新下拉菜单。不知道为什么

父组件

@page "/"

  <table class="table table-sm table-bordered table-striped">
    <thead>
        <tr>
            <th>City</th>
        </tr>
    </thead>
    <tbody>
  @foreach (string c in Cities)
        {
            <tr class="@GetClass(c)">
                <td>@c</td>
            </tr>
        }
    </tbody>
    </table>

<SelectFilter values="@Cities"
              title="@SelectTitle"
              @bind-SelectedValue="SelectedCity"/>

<button class="btn btn-primary"
        @onclick="@(() => SelectedCity = "San Jose")">
    Change
</button>

@functions {
    string[] Cities = new string[] { "New York", "Los Angeles", "Denver", "San Jose" };

    public string SelectedCity { get; set; }

    public string GetClass(string city) =>
        SelectedCity == city ? "bg-info text-white" : "";

     [Parameter]
    public string SelectTitle { get; set; }
    
}

子组件

<div class="form-group">
    <label for="select-@Title">@Title</label>
    <select name="select-@Title"
            class="form-control"
           @onchange="HandleSelect"
            value="@SelectedValue"
            @attributes="Attrs">
        <option disabled selected>Select @Title</option>
        @foreach (string val in Values)
        {
            <option value="@val" selected="@(val == SelectedValue)">@val</option>
        }
    </select>
</div>

@code {
    [Parameter]
    public IEnumerable<string> Values { get; set; } = Enumerable.Empty<string>();

    public string SelectedValue { get; set; }
    [Parameter]

    public string Title { get; set; } = "Placeholder";

    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string, object> Attrs { get; set; }

    [Parameter]
    public EventCallback<string> SelectedValueChanged { get; set; }

    public async Task HandleSelect(ChangeEventArgs e)
    {
        SelectedValue = e.Value as string;
        await SelectedValueChanged.InvokeAsync(SelectedValue);
    }
}

【问题讨论】:

    标签: c# asp.net-core .net-core blazor


    【解决方案1】:

    您的子组件缺少Parameter 属性。

        [Parameter]
        public string SelectedValue { get; set; }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2021-04-06
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2020-11-17
      相关资源
      最近更新 更多