首页 > 解决方案 > Blazor 父组件能否知道其中有多少子组件?

问题描述

我正在创建 2 个 blazor 组件:AlertMessageAlertMessageGroup. AlertMessageGroup旨在包含其中的多个AlertMessage组件。我想AlertMessageGroup有基于AlertMessages 的数量和类型的显示逻辑(AlertMessageType是一个AlertMessage参数,可能会引用一个枚举值)。

父组件(例如AlertMessageGroup)是否有可能知道它包含多少子组件(例如AlertMessage),并有基于此的显示逻辑?

(我会补充一点,理想情况下,我希望能够使用一个AlertMessage独立的,AlertMessageGroup如果我不想的话,不必将它包含在其中)

标签: c#componentsblazor.net-core-3.0blazor-client-side

解决方案


您可以在 AlertMessageGroup 组件中定义 AlertMessage 组件的集合,将捕获的组件引用 ( this ) 传递给 AlertMessage,该引用应在其 OnInitialized 生命周期事件中将自身添加到 AlertMessageGroup。

AlertMessage.razor 的代码片段

[CascadingParameter]
public AlertMessageGroup ContainerParent { get; set; }


protected override void OnInitialized()
{
    ContainerParent.AddChild(this);
}

AlertMessageGroup.razor 的代码片段

// 将组件引用传递给子组件

 <CascadingValue Value=this>

    </CascadingValue>

    @code {
    // Code to add add the children to the parent...

    }

希望我清楚...


推荐阅读