Blazor(.NET6)中如何从Dynamic Component获取组件值?
解决Blazor Dynamic Component获取值的问题
核心思路
要从动态组件中获取值,关键是获取动态组件的实例引用,之后直接访问组件的公开属性即可。针对你加载多个动态组件的场景,可以用集合存储每个组件的实例,提交时遍历集合读取值。
修改后的代码示例
1. 保持TextBoxComponent不变
@Label: <input type="text" style="margin: 5px;" @bind-value="@TextBoxValue"/> @code{ public string Label { get; set; } public string TextBoxValue { get; set; } }
2. 修改Index页面(支持单个/多个动态组件)
@page "/" @foreach (var component in dynamicComponents) { <DynamicComponent Type="component.ComponentType" @ref="component.ComponentInstance" /> } <button class="btn btn-primary" @onclick="SaveToDatabase">Submit</button> @code { // 用类存储动态组件的类型和实例,支持多个组件 private List<DynamicComponentItem> dynamicComponents = new(); protected override void OnInitialized() { // 添加多个动态组件示例(可根据业务逻辑动态添加) dynamicComponents.Add(new DynamicComponentItem { ComponentType = typeof(TextBoxComponent) }); dynamicComponents.Add(new DynamicComponentItem { ComponentType = typeof(TextBoxComponent) }); } private void SaveToDatabase() { foreach (var item in dynamicComponents) { // 强转为目标组件类型,读取属性值 if (item.ComponentInstance is TextBoxComponent textBoxComp) { var inputValue = textBoxComp.TextBoxValue; // 这里执行插入数据库逻辑 Console.WriteLine($"获取到值:{inputValue}"); } } } // 辅助类:存储动态组件的类型和实例 private class DynamicComponentItem { public Type ComponentType { get; set; } public ComponentBase ComponentInstance { get; set; } } }
关键说明
- 使用
@ref绑定DynamicComponent的实例到ComponentBase类型变量,所有Blazor组件都继承自ComponentBase。 - 多组件场景下,用集合存储每个组件的类型和实例,提交时遍历处理即可。
- 如果存在多种类型的动态组件,读取值时通过
is关键字判断组件类型,强转后再访问对应属性。
关于AppState的补充
如果想用状态管理方式,需要确保:
- AppState以单例方式注入(在Program.cs中注册为
AddSingleton<AppState>)。 - 动态组件中绑定AppState属性时,使用双向绑定或在值变化时主动更新AppState。
- 父页面监听AppState的变化(比如实现
INotifyPropertyChanged),确保提交时能拿到最新值。不过这种方式不如直接获取组件实例直接,更适合跨组件共享状态的场景。
内容的提问来源于stack exchange,提问作者Optimus Prime
相关产品推荐
相关产品推荐

