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

Blazor中点击按钮首次渲染Notification组件,再次点击不渲染的原因及解决方法

Blazor中Notification组件首次渲染正常,再次点击按钮无法渲染的问题解决

问题原因

  1. 子组件直接修改参数,未同步父组件状态:子组件的ShowAlert是标记为[Parameter]的属性,属于父组件传递的外部状态。关闭弹窗时子组件直接修改自身的ShowAlert为false,但父组件的ShowAlert值并未更新。再次点击按钮时,父组件只是将ShowAlert从true设为true,状态无变化,Blazor的变更检测机制不会触发组件渲染。
  2. 原生事件绑定未触发Blazor状态检测:子组件关闭按钮使用原生onclick而非Blazor的@onclick,点击后不会触发组件状态变更检测,导致UI无法同步更新。

解决方案

核心思路是让父组件统一控制状态,子组件通过回调通知父组件更新状态,同时修复事件绑定方式:

修改后的代码

父组件(Home.razor)

<button type="button" class="btn btn-sm bg-juice text-light rounded-circle float-start" @onclick="CheckProductVersion">
  <!-- 按钮图标/文本 -->
</button>

<Notification ShowAlert="@ShowAlert" AlertClass="@AlertClass" AlertMessage="@AlertMessage" OnClose="CloseNotification" />

@code {
    private bool ShowAlert { get; set; }
    private string AlertClass { get; set; } = "alert-info";
    private string AlertMessage { get; set; }

    private async Task CheckProductVersion()
    {
        // 先重置状态,确保从false到true的切换能触发渲染
        ShowAlert = false;
        await Task.Delay(1);
        
        try
        {
            await UpdateWorker.CheckUpdate();
            AlertClass = "alert-success";
            AlertMessage = "版本更新完成";
        }
        catch (Exception)
        {
            AlertClass = "alert-danger";
            AlertMessage = "版本更新失败";
        }
        finally
        {
            ShowAlert = true;
        }
    }

    private void CloseNotification()
    {
        ShowAlert = false;
    }
}

子组件(Notification.razor)

@if (ShowAlert)
{
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-12 col-md-6 col-lg-4 col-xl-4">
                <div class="alert @AlertClass mt-2 p-0" role="alert">
                    <button type="button" class="btn" @onclick="HandleClose">
                        <span class="bi-x-circle"></span>
                    </button>
                    @AlertMessage
                </div>
            </div>
        </div>
    </div>
}

@code {
    [Parameter] public bool ShowAlert { get; set; } = false;
    [Parameter] public string AlertClass { get; set; } = "alert-info";
    [Parameter] public string AlertMessage { get; set; }
    [Parameter] public EventCallback OnClose { get; set; }

    private async Task HandleClose()
    {
        await OnClose.InvokeAsync();
    }
}

关键说明

  • 子组件通过EventCallback将关闭事件传递给父组件,由父组件统一控制ShowAlert状态,保证父子组件状态同步。
  • 父组件点击按钮时先将ShowAlert设为false,再设为true,确保状态发生明确变更,触发Blazor的组件渲染。
  • 替换原生onclick为Blazor的@onclick,确保点击事件能触发组件的状态变更检测。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:22:04