Blazor:如何创建可重用的渲染片段?

标签 blazor

我经常使用以下标记:

<SfDropDownList DataSource="@Model.Customers" TItem="Customer" TValue="Customer">
    <DropDownListTemplates TItem="Customer">
        <ItemTemplate Context="customer">
            <span>@customer.Name</span><span class="float-right">@customer.Site</span>
        </ItemTemplate>
    </DropDownListTemplates>
</SfDropDownList>

如何在多个组件中重复使用具有相同参数的 DropDownListTemplates?

我在想,我创建了一个继承自 DropDownListTemplates 的自定义类:

@inherits DropDownListTemplates<Customer>
@code { 
    override void OnAfterRender(bool firstRender)
    {
        // this.ItemTemplate = ??
        base.OnAfterRender(firstRender);
    }
}

但是如何在基类中设置作为 RenderFragment 参数的 ItemTemplate?

我想避免将 SfDropDownList 包装到自定义组件中

最佳答案

您可以为 RenderFragment 参数设置默认值,如下所示。

@ChildContent

@code {
    [Parameter] public RenderFragment ChildContent {get; set;} = @<p>Some text here</p>;
}

来源:blazor-university.com


编辑补充:你也可以在代码中定义一个可重用的RenderFragment

public static RenderFragment SayHello = __builder =>
{
    <h1>Hello!</h1>
};

RenderFragment 委托(delegate)也可以接受参数。

<div class="chat">
    @foreach (var message in messages)
    {
        @DisplayChatMessage(message)
    }
</div>

@code {
    RenderFragment<ChatMessage> DisplayChatMessage = message => __builder =>
    {
        <div class="chat-message">
            <span class="author">@message.Author</span>
            <span class="text">@message.Text</span>
        </div>
    };
}

来源:ASP.NET Core Blazor Web Assembly Performance Best Practices

关于Blazor:如何创建可重用的渲染片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64556105/

相关文章:

.net - 输入密码 Blazor 表单

asp.net-core - 为什么.cshtml更改后页面刷新后不更新

input - 如何将时间类型的输入与 blazor 绑定(bind)

c# - 如何在 Blazor 中创建区域?

c# - CS1929 'IHttpClientFactory' 不包含 'GetFromJsonAsync' 的定义

razor - @RenderSection 在 Blazor 中等效?

c# - 如何将输入从 Blazor 组件传递到 Core MVC Controller ?

c# - 如何在 blazor 组件中显示来自后端的自定义引导警报

asp.net-core - Blazor:如何从子组件中的事件中获取发送者

javascript - 带有 <NavLink> 的 Blazor 子菜单