I'm trying to accomplish something like the code below but I can't seem to figure out how to do it.
@page "/"
<div>@test</div>
@code {
[Parameter]
public string Animal { get; set; }
private BaseComponent test { get; set; }
protected override async Task OnInitializedAsync()
{
switch (Animal)
{
case "Cat": test = <Cat>Fluffy</Cat>; break;
case "Dog": test = <Dog>Woff</Dog>; break;
default: test = <p>None</p>
}
}
I also want to be able to put components in a dictionary like new Dictionary<string, BaseComponent> { {"cat", <Cat>test</Cat> }}
any ideas?
It is possible with RenderFragments:
private Dictionary<string, RenderFragment> switcher
= new Dictionary<string, RenderFragment>(StringComparer.CurrentCultureIgnoreCase)
{
{ "cat" , __builder => { <Cat> It's a Cat </Cat> } },
{ "dog" , __builder => { <Dog> It's a Dog </Dog> } },
};
and then outside of @code,
@switcher["Cat"]
But if this is the best solution depends very much on the exact use-case, and how much flexibility is desired in using the <Animal>
tags.
You could for instance replace the above with a <ShowAnimal Animal="Cat" />
component and implement that with a (big) switch statement in the markup section.
@_content
@code {
[Parameter]
public string Animal { get; set; }
RenderFragment _content => Animal switch
{
"Cat" => @:@{ <Cat>Fluffy</Cat> }
,
"Dog" => @:@{ <Dog>Woff</Dog> }
,
_ => @:@{ <p>None</p> }
};
}
Switch comma's currently must to be on the next line due to a parsing bug.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.