如何在Blazor中创建Razor Page组件列表并实现动态渲染
Blazor动态渲染组件列表实现方案
你可以通过以下两种常用方案实现需求:
方案1:使用RenderFragment列表(无参数组件优先选)
直接将组件封装为渲染片段存入列表,渲染时直接输出即可,完整代码如下:
@page "/" @inject IJSRuntime JSRuntime <h1 style="text-align:center;color:red" >Hey :)</h1> <br /> @* 遍历渲染组件列表 *@ @foreach (var component in ComponentList) { @component } @code { // 定义组件渲染片段列表,直接写入组件标签即可 private List<RenderFragment> ComponentList = new() { @<Counter />, @<NewCounter />, @<AnotherVersion /> }; }
注意事项
如果你坚持使用for循环而非foreach,需要额外捕获循环变量避免闭包问题:
@for(int i = 0; i < ComponentList.Count; i++) { // 定义局部变量捕获当前索引,避免所有循环共用同一个i变量导致渲染错误 var currentIndex = i; @ComponentList[currentIndex] }
方案2:使用DynamicComponent(需要动态传参时选用)
如果你的组件需要传递不同的参数,可使用.NET 6及以上版本内置的DynamicComponent组件,存储组件类型即可实现动态渲染:
@page "/" @inject IJSRuntime JSRuntime <h1 style="text-align:center;color:red" >Hey :)</h1> <br /> @foreach (var compType in ComponentTypeList) { <DynamicComponent Type="@compType" Parameters="@GetComponentParams(compType)" /> } @code { // 存储组件的类型集合 private List<Type> ComponentTypeList = new() { typeof(Counter), typeof(NewCounter), typeof(AnotherVersion) }; // 根据组件类型返回对应参数,无参数组件返回空字典即可 private Dictionary<string, object> GetComponentParams(Type compType) { if (compType == typeof(Counter)) { // 示例:给Counter组件传递InitialValue参数 return new Dictionary<string, object> { { "InitialValue", 10 } }; } return new Dictionary<string, object>(); } }
内容的提问来源于stack exchange,提问作者SoyNeko
相关产品推荐
相关产品推荐

