我需要使用 child從我的父組件上的 stockcomponents 中獲取計數 。對于此代碼 Count 為 0 但實際上資料有更多
<Heading Size="HeadingSize.Is4">Count @ItemCount Entries</Heading>
<StockComponent @ref=stockComponent />
StockComponent stockComponent;
int ItemCount ;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender)
{
ItemCount = stockComponent.Count();
StateHasChanged();
}
}
** 我的股票組件 **
private int count;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if(firstRender)
{
Items = await db.Item.ToListAsync();
count = Items.Count;
StateHasChanged();
}
}
public int Count ()
{
return count;
}
uj5u.com熱心網友回復:
您需要雙向系結。還:
- 獲取物品
OnInitializedAsync() - 你不必打電話
StateHasChanged()
uj5u.com熱心網友回復:
你編碼的方式是錯誤的。您需要做的是創建一個從子級到父級的單向資料系結(Child-to-parent binding)。您的子組件可能看起來像這樣:
StockComponent.razor
<button class="btn btn-primary" type="button"
@onclick="Increment">Increment<button>
@code
{
private int count;
private List<int> Items;
[Parameter]
public int Count { get; set; }
[Parameter]
public EventCallback<int> CountChanged { get; set; }
private async Task Increment()
{
count ;
await CountChanged.InvokeAsync(count);
}
// Note: You shouldn't use the life cycle OnAfterRenderAsync method as you
// do. Instead, you should use the OnInitializedAsync method, which is called
// only once, when the component is created, and initialized with values.
protected override async Task OnInitializedAsync()
{
Items = await db.Item.ToListAsync();
count = Items.Count;
await CountChanged.InvokeAsync(count);
}
}
父組件:Index.razor
<div>Count: @ItemCount Entries</div>
<StockComponent @bind-Count="ItemCount" />
@code
{
private int ItemCount;
}
復制并測驗...
閱讀檔案中的組件系結
我如何從 blazor 中的子組件獲取屬性
通過定義引數屬性和事件回呼。您不能也不應該捕獲對組件的參考 (@ref),然后初始化其屬性。您可能會收到錯誤或至少是警告。僅當您要呼叫執行操作(例如在被呼叫組件中顯示對話框)的方法時,才使用對組件的參考 (@ref)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/337262.html
上一篇:如何通過SSH訪問遠程(遠程服務器上的本地gitlab實體)存盤庫?
下一篇:無法為具有不同于xyz.com/api/webhooks/incoming/*的路由的asp.net通用webhooks設定URI
