簡體   English   中英

如何從 blazor 中的子項調用父 razor 組件中的 function?

[英]How to call a function in a parent razor component from a child item in blazor?

我想按照Microsoft 文檔中的示例創建一個模板化表格組件。

這里我想給表格添加一個排序function:

// This is a function in the code-behind of TableTemplate.razor
public void SortSourceList(/*some args*/)
{
    // sort based on given args
}

問題如下。 我希望孩子們可以訪問這個 function,例如TableHeader項目:

 @page "/somepage
 <TableTemplate Items="pets" Context="pet">
    <TableHeader>
        <th>
             <button class="btn btn-outline-secondary mr-2" 
                 @onclick=<!--call the sorting function from here-->>
        </th>
    </TableHeader>
    <RowTemplate>
        ...
    </RowTemplate>
</TableTemplate>
@code{ // page related code - don't want to handle anything concerning the table here }

我知道這可以通過將TableTemplate的實例作為CascadingParameter傳遞下來來完成,但是如何在正常的 html 項目中獲得它,這不是 razor 組件? 此外,我不一定要將TableTemplate實例作為 class 屬性添加到任何子組件(據我所知,訪問級聯參數需要它嗎?),所以我想知道是否可以通過 function 或事件直接?

您可以在子組件內部使用 EventCallback 並調用父組件 function:

家長

<_ChildComponentCall parentFunction="SortSourceList"></_ChildComponent>

public void SortSourceList(/*some args*/)
{
    // sort based on given args
}

孩子

<TableTemplate Items="pets" Context="pet">
    <TableHeader>
        <th>
             <button class="btn btn-outline-secondary mr-2" 
                 @onclick="() => parentFunction.InvokeAsync()"
        </th>
    </TableHeader>
    <RowTemplate>
        ...
    </RowTemplate>
</TableTemplate>
@code
[Parameter]
public EventCallback parentFunction { get; set; }

運行 function 后,您可以將排序數據保存在服務變量中,並從子項中調用該變量。

也有一種簡單直接的方法,就是讓 TableHeader 也有類型。

TableTemplate.razor中的更改

  <thead>
    <tr>@TableHeader(this)</tr>
  </thead>

@code {
[Parameter]
public RenderFragment<TableTemplate<TItem>>? TableHeader { get; set; }

然后像這樣使用它

<TableTemplate Items="pets" >
  <TableHeader Context="table">

       <button @onclick="() => table.SortSourceList(/* args */)" />

  </TableHeader>

  <RowTemplate Context="pet">
     ...
  </RowTemplate>
</TableTemplate>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM