Best way to get list of child components in Blazor

↘锁芯ラ 提交于 2020-06-29 05:07:39

问题


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.


回答1:


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: In the Parent add a wrapper around your @ChildContent to add a cascading value pointing to itself.

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

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

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

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

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

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



来源:https://stackoverflow.com/questions/62057899/best-way-to-get-list-of-child-components-in-blazor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!