![](/img/trans.png)
[英]How do I call a method in one Blazor (parent) component from another Blazor (“child”) component?
[英]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.