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.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다