Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

Is it possible to call a Blazor component through a parameter passed to a component?

I would like to be able to send the name of a Blazor component to another component and have it render. Something like:

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

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

Where Navigation1.razor is a component rendered in a certain place within the ContentLeftNav.razor component. I've seen articles where switch is recommended to alternate between components, but I'd like to avoid writing out a switch statement for all possible navigation components. Is what I'm wanting to do even possible?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would do it like this:

Have your ContentLeftNav component specify multiple render fragments. For example:

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

Then use it like:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...