如何从 blazor 中的 child 项调用 parent razor 组件中的函数?

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

我想按照 microsoft documentation 中的示例创建模板化 table 组件。

这里我想给table添加一个排序功能:

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

问题如下。我希望可以从 children 访问此功能,例如 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 项目中获得它,这不是剃须刀组件?此外,我不一定要将 TableTemplate 实例作为 class 属性 添加到任何 child 组件(据我所知,这是访问级联所必需的参数?),所以我想知道是否可以直接传递函数或事件?

您可以在 child 组件中使用 EventCallback 并调用 parent 函数:

Parent

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

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

Child

<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; }

在 运行 函数之后,您可以将排序数据保存在服务变量中,并从 child.

调用该变量

还有一个简单直接的方法,就是让 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>