繁体   English   中英

Blazor 刷新子组件列表

[英]Blazor refresh List of Child Component

考虑以下呈现 ChildComponent 列表的ChildComponent ParentComponent

<input type="date" @bind-Value="date" />
<button type="button" @onclick="ChangeDate"> Filter </button>

foreach(var i in list)
{
   <ChildComponent Id="i.Id" Date="date" />
}

@code{
   List<int> list; //a list of ids for this example
   DateTime date = DateTime.Today; //date ChildComponent should be filtered by
   
   async Task ChangeDate()
   {
      //What do I write here to call StateHasChanged() on ChildComponents?
   }
}

我如何从ParentComponent调用所有ChildComponentStateHasChanged()

一般来说,这是服务的工作。 您的数据位于(我们称之为)DateService 中。 DateService 包含具有 ID 和日期的项目列表。 当您在“页面”组件中更改日期(在任何或所有列表项中)时,您会触发您在服务中设置的 ListHasChanged 事件/委托。 每个ChildComponent使用依赖注入来获取服务,并在OnInitializedAsync中为事件注册一个内部事件处理程序。 如有必要,事件处理程序会重新呈现。 注意:始终使用 Invoke 调用StateHasChanged - 您永远无法保证哪个线程正在使用事件处理程序调用它。 我已经展示了一个通用的事件处理程序,它重新渲染了一个组件。

protected async void RenderAsync(object sender, EventArgs e) => await this.InvokeAsync(StateHasChanged);

如果需要,我会发布一些更详细的代码。

此处有关服务和 DI 的 MS 详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM