c# - 将附加数据传递给 Blazor 组件中的通用 RenderFragment

标签 c# asp.net-core generics blazor

我有一个简单的 Blazor 组件,它遍历一个通用列表:

@typeparam TItem;

 @foreach (var item in List)
        {
            @ElementTemplate(item); // What code should be here to pass i to the ElementTemplate????
            i++;
        }

@code {
    int i = 0;


    [Parameter] public List<TItem> List { get; set; }
    [Parameter] public RenderFragment<TItem> ElementTemplate { get; set; }
  }

我有另一个简单的组件,它将获取一个项目和一个索引来呈现数据(员工):

<div> @Index . @Person.Name </div>

@code{
    [Parameter] public Person { get; set; }
    [Parameter] public int Index { get; set; }

}

在我的主页中,我有以下内容:

<GenericList List="employees">
    <ElementTemplate>
        <Employee Person="context" Index="?"></Employee>
    </ElementTemplate>
</GenericList>

正如您所见,Employee 组件需要一个 Index 参数,我如何从 GenericList 组件传递 Index? 在此示例中,变量“i”应传递给 ElementTemplate 以及 Generic TItem 对象本身。

最佳答案

我发现快速/简单的方法是使用元组作为 RenderFragment 上下文:

@foreach (var item in List)
{
  @ElementTemplate((item,i));
  i++;
}

@code {
  int i=0;
  [Parameter] public List<TItem> List { get; set; }
  [Parameter] public RenderFragment<(TItem item, int index)> ElementTemplate { get; set; }
}

然后你的标记变成:

<GenericList List="employees">
    <ElementTemplate>
        <Employee @key=@context.index Person=@context.item Index=@context.index></Employee>
    </ElementTemplate>
</GenericList>

如果您愿意,可以在 GenericList 中使用实用程序类而不是元组。

关于c# - 将附加数据传递给 Blazor 组件中的通用 RenderFragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64206500/

相关文章:

c# - 在 C# 中从 SQLServer 查询日期?

c# - 如何在 .net 中生成 UTF-8 字符集中的所有字符

c# - 使用 Datastax Cassandra .NET 客户端创建表

c# - 将测试结果文档上传到 Azure 测试计划或 TFS 2018 中的测试中心

c# - 无法在单元测试中设置 AutoMapper,无法加载文件或程序集 Microsoft.AspNetCore.Mvc.ViewFeatures

swift - 如何在 swift 中为浮点值编写通用函数

Java泛型,不能使用任何可迭代对象的参数创建构造函数

c# - POST 方法的参数始终为 null

c# - FluentScheduler 构造函数中的依赖注入(inject)

java - 将 Java 数组和基元 (double[][]) 重构为集合和泛型 (List<List<Double>>)