簡體   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