在Blazor中获取子组件列表的最佳方法 [英] Best way to get list of child components in Blazor

查看:564
本文介绍了在Blazor中获取子组件列表的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要在父组件的OnAfterRenderAsync方法中获取子组件的列表,但是,我们不知道该怎么做. 我们尝试使用RenderBuilderGetFrames,但这始终为null. 我们有带有N个分割区域的拆分器组件作为子组件,我们需要通过OnAfterRenderAsync方法获取父组件中的所有区域.

We need to get list of child components in OnAfterRenderAsync method of parent component but, we don't know how to do that. We try with RenderBuilder and GetFrames but this is always null. We have Splitter component with N Split Areas as child components and we need to get all areas in Parent component, in OnAfterRenderAsync method.

推荐答案

如果您具有类型X的父组件,并且想要引用所有类型Y的紧密耦合子代(例如TabControl和TabPages),则可以做到这一点.

If you have a parent component of type X and you want to references to all tightly coupled children of type Y (for example, TabControl and TabPages) then you can do this.

1:在父项"中,在@ChildContent周围添加一个包装器,以添加指向自身的级联值.

1: In the Parent add a wrapper around your @ChildContent to add a cascading value pointing to itself.

<CascadingValue Value=@this>
  @ChildContent
</CascadingValue>

2:在孩子中,您可以通过CascadingParameter

2: In your children you can consume that value via a CascadingParameter

@code
{
  [CascadingParameter]
  public YourParentComponent ParentComponent { get; set; }
}

3:您的孩子可以随后将其存在告知父母

3: Your children can then notify their parent of their existence

protected override void OnInitialized()
{
    if (ParentComponent == null)
      throw .............("Must be used within MyParentComponent");
    MyParentComponent.AddChild(this);
}

如果子组件是有条件渲染的,则让它们实现IDisposable,以便它们可以通知父组件将其从其列表中删除.

If your child components are conditionally rendered then have them implement IDisposable so they can notify the parent to remove them from its list.

在Blazor University上有一个示例,展示了如何创建TabControl-

There's an example on Blazor University showing how to create a TabControl - https://blazor-university.com/templating-components-with-renderfragements/creating-a-tabcontrol/

这篇关于在Blazor中获取子组件列表的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆