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

Blazor 8 InteractiveServer模式下OnInitializedAsync获取组件引用方案

Blazor 8 InteractiveServer模式下级联参数失效的可靠替代方案

Blazor 6/7 原有实现

在Blazor 6和7版本中,_Host.cshtml配置如下:

<head>
    <component type="typeof(HeadOutlet)" render-mode="Server" />
</head>
<body>
    <component type="typeof(App)" render-mode="Server" param-InitialState="initialTokenState" />
</body>

基于此,在MainLayout.razor中引入PopupMessageBox组件,用于在OnInitializedAsync()处理过程中显示弹窗(如用户无权限访问对应URL参数的页面时,弹窗提示后跳转)。相关组件代码如下:

PopupMessageBox.razor

<CascadingValue Value="this" IsFixed="true">
    @ChildContent
</CascadingValue>

<DxPopup @ref="MessageBoxPopup"
    <!-- 其他配置内容 -->
</DxPopup>

MainLayout.razor

<main class="@pageClass">
    <PopupMessageBox>
        <div class="main-content">
            @Body
        </div>
    </PopupMessageBox>
</main>

需要使用弹窗的页面razor.cs文件中,通过级联参数注入组件引用:

[CascadingParameter]
protected PopupMessageBox PopupMessageBox { get; set; } = default!;

Blazor 8 InteractiveServer模式下的问题

升级到Blazor 8的InteractiveServer模式后,上述级联参数方式不再可靠:经测试,OnInitializedAsync()第二次调用时,PopupMessageBox参数为空。

虽有将级联参数替换为服务的示例(如AuthenticationStateTask),但此处需要的是组件的@ref引用,且需在OnInitializedAsync()中可靠获取。尝试调用Task.Yield()有时能填充参数,但无保障;OnAfterRenderAsync()也并非安全或合适的时机(可能在OnInitializedAsync()完成前调用)。

Blazor 8 补充配置

Blazor 8中无_Host.cshtml文件,相关配置如下:

App.razor

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="bootstrap/bootstrap.min.css" />
    <link rel="stylesheet" href="app.css" />
    <link rel="stylesheet" href="BlazorWebApp.styles.css" />
    <link rel="icon" type="image/png" href="favicon.png" />
    <HeadOutlet @rendermode="InteractiveServer" />
</head>

<body>
    <Routes @rendermode="InteractiveServer" />
    <script src="_framework/blazor.web.js"></script>
</body>

</html>

Routes.razor

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(Layout.MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
</Router>

请问有什么可靠的实现方案?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 21:23:11