name: render-info description: 使用Blazor中的RendererInfo类来检测渲染上下文和交互性。
在Blazor中使用RendererInfo
Blazor中的RendererInfo类提供了有关正在执行组件的渲染器的运行时信息。它对于检测组件是在交互式还是静态模式下运行,以及识别特定的渲染平台(例如,服务器、WebAssembly、WebView)特别有用。
关键属性
IsInteractive
- 类型:
bool - 描述: 指示组件当前是否在交互式渲染模式下运行。
- 用法: 使用此属性可以有条件地渲染需要交互性的UI元素,例如在静态服务器端渲染(SSR)或预渲染期间禁用按钮或显示加载指示器。
@if (!RendererInfo.IsInteractive)
{
<p>正在连接...</p>
}
else
{
<button @onclick="HandleClick">点击我</button>
}
Name
- 类型:
string - 描述: 返回渲染器的名称。
- 常见值:
"Static":在静态服务器端渲染(SSR)模式下运行。"Server":在交互式服务器模式(SignalR)下运行。"WebAssembly":在交互式WebAssembly模式下运行。"WebView":在Blazor混合应用程序(MAUI、WPF、WinForms)中运行。
<p>当前渲染模式:@RendererInfo.Name</p>
常见场景
1. 在预渲染期间禁用输入
当组件在服务器上预渲染时,事件处理程序(如@onclick)不会激活。您可以使用RendererInfo.IsInteractive来禁用输入,直到交互式运行时接管。
<button @onclick="Submit" disabled="@(!RendererInfo.IsInteractive)">
提交
</button>
2. 为静态与交互式渲染不同的内容
您可能希望为静态SSR显示一个简单的HTML表单,而为交互式模式显示一个丰富的交互式组件。
@if (RendererInfo.Name == "Static")
{
<form action="/search" method="get">
<input name="q" />
<button type="submit">搜索</button>
</form>
}
else
{
<SearchComponent />
}
相关概念
AssignedRenderMode:ComponentBase上的一个属性,告诉您分配给组件的渲染模式(例如,InteractiveServer、InteractiveWebAssembly、InteractiveAuto)。请注意,在静态渲染期间,AssignedRenderMode可能为null。
重要说明
RendererInfo在.NET 8.0及更高版本中可用。- 它是一个静态类,因此您可以直接在Razor标记或C#代码中访问它,无需注入。