是否可以通过传递给组件的参数来调用 Blazor 组件?

时间:2021-01-12 15:13:57

标签: blazor blazor-server-side

我希望能够将 Blazor 组件的名称发送到另一个组件并使其呈现。类似的东西:

@page "/"
@using MyProject.Shared.Navigation

<ContentLeftNav UseNav="Navigation1">
Content
</ContentLeftNav>

其中 Navigation1.razor 是在 ContentLeftNav.razor 组件中某个位置呈现的组件。我看过推荐 switch 在组件之间交替使用的文章,但我想避免为所有可能的导航组件写出 switch 语句。我想做的事情有可能吗?

2 个答案:

答案 0 :(得分:0)

我会这样做:

让您的 ContentLeftNav 组件指定多个渲染片段。例如:

<h3>ContentLeftNav</h3>
<div id="Content-left-body">
    @Content
</div>
<div id="Content-left-nav">
    @Navigation
</div>

@code {
    [Parameter] public RenderFragment Navigation { get; set; }
    [Parameter] public RenderFragment Content { get; set; }
}

然后像这样使用它:

<ContentLeftNav>
    <Navigation>
        @if (true)
        {
            <p>Some navigation content</p>
        }
        else
        {
            <p>Some other navigation content</p>
        }
    </Navigation>
    <Content>
        <p>Some other content</p>
    </Content>
</ContentLeftNav>

答案 1 :(得分:0)

这是另一种选择。这不是很好,但它会起作用:

ContentLeftNav.razor

<nav>
   @RenerNav()
</nav>
<div>
   @ChildContent
</div>

@code {
   [Parameter] public Type NavComponent {get; set; }
   [Parameter] public RenderFragment ChildContent { get; set; }
    
    private RenderFragment RenderNav() => builder =>
    {
        builder.OpenComponent(0, ComponentToRender);
        builder.CloseComponent();
    };
}
Index.razor

@page "/"
@using MyProject.Shared.Navigation

<ContentLeftNav NavComponent="@typeof(Navigation1)">
Content
</ContentLeftNav>

渲染 ContentLeftNav 时,您可以发送任何组件的类型,ContentLeftNav 将渲染该组件的实例。