动态呈现 Blazor 组件的推荐方法是什么?

What's the recommended way of rendering a Blazor component dynamically?

我是 Blazor 的新手,具有基本的 Angular 和 Vue.js 经验。我想渲染一个多态组件列表:

<ul>
    @foreach (fruit of fruits) 
         <li>HOW DO I RENDER FRUIT HERE??? </li> // render the fruit component
</ul>

@code {
   // Each member in the list is a subtype of Fruit
   var fruits = List<FruitComponent> {
       new PearComponent(),
       new AppleComponent()'
       new BananaComponent(),
       new RasberryComponent()
}

据我所知,有几种方法可以实现这一点,每种方法都有自己的缺点。一个不常见的建议使用未记录的 API 调用,它可能会在没有通知的情况下被弃用,但它似乎几乎是理想的。另一个建议在代码中发出标记,这会带回编写 ASP.NET 服务器控件的单调乏味。最后,最常见的建议是使用条件标记,虽然非常简单,但它将渲染代码耦合到它正在渲染的组件。

我读过的大部分文档可能已经过时并且不再相关。随着 Blazor 的正式发布,推荐的实现方式是什么?

您可以使用检查类型的 switch 语句。 您可以在每个案例中放置组件,或根据需要渲染您的 li。

<ul>
    @foreach (fruit in fruits)
    {
        switch(fruit)
        {
            case PearComponent p:
                <PearComponent ParameterOfSomeSort="p"></PearComponent>
                <li>Or render pears like this, if you want the li in it</li>
                break;
            case AppleComponent a:
                <AppleComponent></AppleComponent>
                break;
            case BananaComponent b:
                <BananaComponent></BananaComponent>
                break;
            case RaspberryComponent r:
                <RaspberryComponent></RaspberryComponent>
                break;
        }
    }
</ul>

您必须创建一个 RenderFragment,并将其用作多态组件的渲染器...我使用默认的 Blazor 模板计数器组件作为父级 (CounterParent),然后 CounterChild 继承了 CounterParent。我希望它有所帮助!此致!

@page "/"

@foreach (CounterParent counter in components)
{
    RenderFragment renderFragment = (builder) => { builder.OpenComponent(0, counter.GetType()); builder.CloseComponent(); };
    <div>
        <div>Before the component</div>
        @renderFragment
        <div>Afterthe component</div>
    </div>
}

@code
{
    List<CounterParent> components = new List<CounterParent>() { new CounterParent(), new CounterChild() };
}