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

Blazor .NET MAUI空子组件不渲染但父组件正常问题求助

Blazor继承基组件后子组件无法显示的解决方法

我有一个名为ToggleButtonBaseComponent的Blazor组件,包含C#逻辑、HTML结构和CSS样式,打算作为不同行为切换按钮的基组件。但当我继承它创建一个空的子组件ChildComponent并放到页面中时,子组件完全不显示,直接使用父组件却能正常渲染。

页面中组件引用示例:

<ChildComponent></ChildComponent>
<ToggleButtonBaseComponent></ToggleButtonBaseComponent>
<ToggleButtonBaseComponent></ToggleButtonBaseComponent>

父组件ToggleButtonBaseComponent代码:

@inherits IDisposableComponent;

<style>
    /* 省略样式代码 */
</style>

<button class="toggle-button @(IsToggled ? "toggled-on" : "toggled-off")" @onclick="ToggleClick" style="height:@(Height)px; width:@(Width)px; border-radius:@(BorderRadius)px">
    <span class="circle @(IsToggled ? "toggled-on" : "toggled-off")" style="height:@(Height)px; width:@(Height)px;"></span>
</button>

@code {
    [Parameter]
    public int Width{ get;set;} = 40;

    private int Height { get; set; }
    private int BorderRadius { get; set; }

    protected bool IsToggled 
    {
        get; 
        set; 
    }

    protected override void OnParametersSet()
    {
        Height = Width / 2;
        BorderRadius = Height / 2;
    }

    protected virtual void ToggleClick() { }

    public override void Dispose() { }
}

子组件ChildComponent原代码:

@using ....
@inherits ToggleButtonBaseComponent;

@code {

}

问题原因

Blazor中使用@inherits继承组件时,子组件默认不会自动渲染父组件的HTML结构和内嵌样式,只会继承C#逻辑部分,所以空的子组件没有任何可渲染的内容,自然无法显示。

解决方法

在子组件中添加@base指令,显式告诉Blazor渲染父组件的标记内容:

修改后的子组件代码:

@using ....
@inherits ToggleButtonBaseComponent;

@base

@code {
    // 这里可以添加自定义逻辑,比如重写ToggleClick方法
    // protected override void ToggleClick()
    // {
    //     // 自定义点击行为
    //     IsToggled = !IsToggled;
    // }
}

@base指令会完整继承父组件的HTML结构、内嵌样式,同时保留子组件的C#逻辑。这样子组件就能正常显示出和父组件一致的UI,还能通过重写父类的虚拟方法(比如ToggleClick)实现自定义行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:50:27