![](/img/trans.png)
[英]How to refresh a blazor sub/child component within a main/parent component?
[英]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
調用所有ChildComponent
的StateHasChanged()
?
一般來說,這是服務的工作。 您的數據位於(我們稱之為)DateService 中。 DateService 包含具有 ID 和日期的項目列表。 當您在“頁面”組件中更改日期(在任何或所有列表項中)時,您會觸發您在服務中設置的 ListHasChanged 事件/委托。 每個ChildComponent
使用依賴注入來獲取服務,並在OnInitializedAsync
中為事件注冊一個內部事件處理程序。 如有必要,事件處理程序會重新呈現。 注意:始終使用 Invoke 調用StateHasChanged
- 您永遠無法保證哪個線程正在使用事件處理程序調用它。 我已經展示了一個通用的事件處理程序,它重新渲染了一個組件。
protected async void RenderAsync(object sender, EventArgs e) => await this.InvokeAsync(StateHasChanged);
如果需要,我會發布一些更詳細的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.