【问题标题】:Inverted responsibility for a blazor component parameterblazor 组件参数的反向责任
【发布时间】:2022-02-20 13:16:45
【问题描述】:

看看这个 blazor 服务器页面:

@page "/"

<div>@count</div>

<MyGridComponent Count="@Count" />

@code
{
    private int count { get; set; }
}

网格组件包含一个 IQueryable。用户可以在此组件内应用自定义过滤器。

我想显示记录的数量,处理网格组件之外的自定义过滤器。

是否可以在这个方向(从组件到父组件)传递count参数值?

我尝试过处理一个事件,但是代码很重,我需要为此实现一个方法。

谢谢

【问题讨论】:

  • 2路绑定的代码正好是2行。我向 Blazor 新手推荐以下网站。 blazor-university.com/components/two-way-binding
  • 为什么不在 DI 服务中包含所有数据,并通过事件通知更改。然后任何需要知道更改的人说服务中的 DataSet 只需连接到DataSetChanged 事件并调用StateHasChanged 以刷新服务中记录数的显示。
  • 谢谢,这是个好主意
  • 仅供参考 - 我不久前写了一个类似问题的答案,演示了如何在开箱即用的模板中为 WeatherForecasts 构建这样的服务 - stackoverflow.com/questions/69558006/…

标签: blazor blazor-server-side


【解决方案1】:

你的 MyComponent 应该有 EventCallback,它在每次过滤操作后返回网格中的行数

[Parameter]
public EventCallback<int> RowCount{ get; set; }

private void ApplyCustomFilter(){
    if(RowCount.HasDelegate) RowCount.InvokeAsync(NoOfRowsInGrid);
}

现在您的剃须刀页面可以订阅 MyComponent 中的 RowCount 回调

@page "/"

<div>@count</div>

<MyComponent RowCount="@(count=> // here count will have latest no of rows in grid)"/>

【讨论】:

    【解决方案2】:

    请注意,事件名称完全是变量的名称,并在末尾添加了单词Changed

    Parent.razor

    @page "/"
    
    <div>@count</div>
    
    <MyGridComponent @bind-RowCount="@Count" />
    
    @code
    {
        private int count { get; set; }
    }
    

    Child.razor

    // some markup here
    
    @body
    [Parameter]
    public int RowCount {get; set;}
    [Parameter]
    public EventCallback<int> RowCountChanged {get; set;}
    
    async task Processrows (){
         await RowCountChanged.InvokeAsync(newNumberOfRows);
    }
    

    【讨论】:

    • 不需要@bind-前缀?
    • 是的,你是对的,我已经编辑过了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2021-01-18
    • 2019-10-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多