如何在代码中使用Blazor组件?

时间:2020-07-05 17:17:31

标签: c# razor blazor

我正在尝试完成类似下面的代码的操作,但是我似乎不知道该怎么做。

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

我还希望能够将组件放入像new Dictionary<string, BaseComponent> { {"cat", <Cat>test</Cat> }}这样的字典中

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

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

};

,然后在@code之外,

@switcher["Cat"]

但是,如果这是最佳解决方案,则在很大程度上取决于确切的用例,以及在使用<Animal>标签时需要多少灵活性。

例如,您可以将上述内容替换为<ShowAnimal Animal="Cat" />组件,并在标记部分中使用(大)switch语句来实现。

答案 1 :(得分:4)

渲染片段字典:

@_content

@code {

    [Parameter]
    public string Animal { get; set; }

    RenderFragment _content => Animal switch
    {
        "Cat" => @:@{ <Cat>Fluffy</Cat> } 
,
        "Dog" => @:@{ <Dog>Woff</Dog> } 
,
           _  => @:@{ <p>None</p> } 
    };

}

注意:

由于存在解析错误,当前必须以逗号作为下一行。