继承带类型参数基组件的Blazor组件无法渲染
解决Blazor动态类型基组件无渲染输出的问题
问题分析
代码编译正常但组件无输出,核心原因有两个:
- 派生类未关联组件视图:
ZoomCampaign是纯C#类,仅继承了TableComponentBase<string>基类,但Blazor无法将其与TableComponent.razor的视图模板关联,导致没有渲染内容。 - 行数据方法未返回有效内容:基类的
Rows方法默认返回空列表,即使表头能渲染,表格行也会是空的。
解决方案
调整派生类为Razor组件,继承泛型的TableComponent<TItem>而非纯C#基类,并实现Rows方法返回实际行数据。
修改后的完整代码
TableComponent.razor(保持不变)
@namespace BlazorRepl.UserComponents @inherits TableComponentBase<TItem> @typeparam TItem <div> <table class="table"> <thead> <tr> @foreach (var str in Headers()) { <th>@str</th> } </tr> </thead> <tbody> @foreach (var item in items) { <tr> @foreach (var str in Rows(item)) { <td>@str.ToString()</td> } </tr> } </tbody> </table> </div>
TableComponent.cs(保持不变)
namespace BlazorRepl.UserComponents { using System; using System.Collections.Generic; using Microsoft.AspNetCore.Components; public class TableComponentBase<TItem> : ComponentBase { [Parameter] public List<TItem> items { get; set; } protected virtual List<TItem> Rows(TItem item) { return new List<TItem>(); } protected virtual List<string> Headers() { return new List<string>() { "Placeholder" }; } } }
ZoomCampaign.razor(替换原ZoomCampaign.cs)
@namespace BlazorRepl.UserComponents @inherits TableComponent<string> @code { protected override List<string> Headers() { return new List<string>() { "#", "Name" }; } protected override List<string> Rows(string item) { // 根据传入的item生成行数据,示例返回序号和传入字符串 return new List<string>() { "1", item }; } }
Index.razor(保持不变)
@using BlazorRepl.UserComponents <ZoomCampaign items=@(new List<string> {"test"})/>
关键说明
- 将
ZoomCampaign改为Razor组件后,会自动继承TableComponent.razor的视图模板,同时可重写基类的Headers和Rows方法。 - 重写
Rows方法返回有效数据,确保表格行能显示内容。
内容的提问来源于stack exchange,提问作者ajb101
相关产品推荐
相关产品推荐

