You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中如何将动态生成的组件实例保存到List或数组?

问题解决:Blazor动态渲染组件并保存引用

问题根源

你直接实例化PdfComp类然后循环输出@comp的方式是错误的:Blazor组件的渲染由框架管理,手动new出来的ComponentBase实例没有经过Blazor的初始化、渲染流程,框架只会把它当成普通C#对象调用ToString(),所以页面显示的是组件的类名而非UI内容。

正确实现方案

1. 定义组件参数+引用的模型类

先创建一个类,用来存储每个组件的参数和对应的组件引用:

public class PdfCompItem
{
    // 组件参数
    public string Text { get; set; } = "Missing text";
    public string Type { get; set; } = "noone";
    public int X { get; set; } = 0;
    public int Y { get; set; } = 0;
    // 组件引用(用于后续操作组件实例)
    public PdfComp ComponentRef { get; set; }
}

2. 修改List类型与添加组件方法

把原来的List<PdfComp>改成List<PdfCompItem>,添加组件时只添加参数模型:

private List<PdfCompItem> PdfComponentsList = new List<PdfCompItem>();

public void addPdfComp(int type)
{
    PdfComponentsList.Add(new PdfCompItem
    {
        Text = "some test text",
        Type = type.ToString()
    });
}

3. 正确渲染组件并捕获引用

用Blazor的组件标签渲染,通过@ref捕获组件实例,同时绑定参数:

@foreach (var item in PdfComponentsList)
{
    <div>
        <PdfComp @ref="item.ComponentRef" 
                 text="@item.Text" 
                 type="@item.Type" 
                 _x="@item.X" 
                 _y="@item.Y" />
    </div>
}

可选:实现参数双向同步

如果需要子组件的输入值同步回父组件的模型,修改PdfComp组件添加回调事件(符合Blazor双向绑定规范):

<div class="row p-1 " style="border:solid; ">
<h5>TextComponent</h5>
<div>
    <label>X</label>
    <input type="number" class="col-2" @bind-value="X" @bind-value:event="oninput"/>
    <label>Y</label>
    <input type="number" class="col-2" @bind-value="Y" @bind-value:event="oninput"/>
    <label>Text</label>
    <input type="text" class="col-4" @bind-value="Text" @bind-value:event="oninput"/>
</div>
</div>

@code {
[Parameter]
public string Text { get; set; } = "Missing text";
[Parameter]
public string Type { get; set; } = "noone";
[Parameter]
public int X { get; set; } = 0;
[Parameter]
public int Y { get; set; } = 0;

// 双向绑定回调
[Parameter]
public EventCallback<string> TextChanged { get; set; }
[Parameter]
public EventCallback<int> XChanged { get; set; }
[Parameter]
public EventCallback<int> YChanged { get; set; }
}

父组件渲染时改用@bind-语法实现双向绑定:

<PdfComp @ref="item.ComponentRef" 
         @bind-Text="@item.Text" 
         type="@item.Type" 
         @bind-X="@item.X" 
         @bind-Y="@item.Y" />

效果说明

这样修改后,页面会正确渲染每个PdfComp组件的UI,同时PdfComponentsList里的ComponentRef字段会保存对应组件的实例,后续可以通过它调用子组件的方法或访问属性。

内容的提问来源于stack exchange,提问作者Andi Hincu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 03:54:12