使用DynamicComponent创建一个OneContainer

DynamicComponent是.NET 6中内置的动态渲染组件,比如根据下拉列表或者单选框中选择的内容来呈现组件。其实,基于DynamicComponent可以做很多好玩的事情,比如之前讲到的动态Modal。接下来我将讲下如果创建一个OneContainer组件。有些时候,我们可能会使用多个组件库,而每个组件库可能都有自己的Container,亦或者是我们自己的实现中有多个Container,比如有ModalContainer、NotificationContainer等等,那么我们可能需要在App.razor下面添加多个Container组件。通过利用DynamicComponent,我们可以很方便的添加多个组件库的ContainerOneContainer代码如下:

OneContainer.razor

@foreach(Type type in Components)
{
    <DynamicComponent Type="@type" />
}

@code{
    [Parameter]
    public List<Type> Components { get; set; } = new List<Type>();
}

DynamicComponent有三个参数,但是对于容器而言,一般没有任何参数,因此只用个类型即可。在App.razor中使用时候,如下即可:

<OneContainer Components="new List<Type>{ typeof(ModalContainer), typeof(NotifycationContainer) }" />

效果如下:

至于ModalContainerNotifycationContainer是如何实现的不用关心,这里仅是模拟下而已。

示例代码:BlazorTricks/03-OneContainer at main · zxyao145/BlazorTricks (github.com)

posted @ 2022-01-02 14:20  半野  阅读(379)  评论(0编辑  收藏  举报