c# - Blazor 父组件能否知道其中有多少子组件?
问题描述
我正在创建 2 个 blazor 组件:AlertMessage
和AlertMessageGroup
. AlertMessageGroup
旨在包含其中的多个AlertMessage
组件。我想AlertMessageGroup
有基于AlertMessage
s 的数量和类型的显示逻辑(AlertMessageType
是一个AlertMessage
参数,可能会引用一个枚举值)。
父组件(例如AlertMessageGroup
)是否有可能知道它包含多少子组件(例如AlertMessage
),并有基于此的显示逻辑?
(我会补充一点,理想情况下,我希望能够使用一个AlertMessage
独立的,AlertMessageGroup
如果我不想的话,不必将它包含在其中)
解决方案
您可以在 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...
}
希望我清楚...
推荐阅读
- excel - 在powerpivot中连接两个具有多对多关系的表
- visual-studio-code - Visual Studio Code 和 pylint 未发现模块问题
- javascript - 等待事件未触发
- intel - 带有 Z80 处理器的任何东西都可以运行 Gameboy 游戏吗?
- vba - 不断收到运行时错误“13”:类型不匹配
- c# - 更改类库中的用户设置
- node.js - Nodejs - Apache Cassandra(使用 Datastax 驱动程序)
- sql - 返回 Netezza SQL 中每个组的最大值日期
- ios - Swift4.2:为什么 func gameDidEnd(_:) 不需要使用游戏参数但仍然在函数中声明?
- amazon-web-services - 如何找出 AMI 的 S3 链接