布拉佐尔
- 作者仓库星标 423
- 作者仓库 dotnet-skills
- 领域
- 设计与多媒体
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @managedcode · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 即装即用
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- 未声明(默认跨平台)
- 运行环境要求
- 未检出明确要求
- 检测到的文件与系统行为
-
- 只读
- 网络行为
- 允许外网请求
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
# Blazor
## Trigger On
- building interactive web UIs with C# instead of JavaScript
- choosing between Server, WebAssembly, or Auto render modes
- designing component hierarchies and state management
- handling prerendering and hydration
- integrating with JavaScript when necessary
## Documentation
- [Blazor Overview](https://learn.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-10.0)
- [Render Modes](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-10.0)
- [Performance Best Practices](https://learn.microsoft.com/en-us/aspnet/core/blazor/performance?view=aspnetcore-10.0)
- [State Management](https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-10.0)
- [JS Interop](https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-10.0)
### References
- [patterns.md](references/patterns.md) - Detailed component patterns, state management strategies, and JS interop techniques
- [anti-patterns.md](references/anti-patterns.md) - Common Blazor mistakes and how to avoid them
## Render Modes (.NET 8+)
| Mode | Where It Runs | Best For |
|------|---------------|----------|
| `Static` | Server (no interactivity) | SEO pages, marketing content |
| `InteractiveServer` | Server via SignalR | Real-time apps, thin clients |
| `InteractiveWebAssembly` | Browser via WASM | Offline-capable, client-heavy |
| `InteractiveAuto` | Server first, then WASM | Best of both worlds |
### Applying Render Modes
```razor
@* Per-component *@
@rendermode InteractiveServer
@* Or in App.razor for global *@
<Routes @rendermode="InteractiveAuto" />
```
### InteractiveAuto Architecture
```
First Request:
Browser → Server (Interactive Server) → Fast response
Subsequent Requests:
Browser → WASM (downloaded in background) → No server needed
```
## Workflow
1. **Choose render mode based on requirements:**
- Need SEO? Start with Static or prerendering
- Need real-time? Use InteractiveServer
- Need offline? Use InteractiveWebAssembly
- Want both? Use InteractiveAuto
2. **Design components for reusability:**
- Small, focused components
- Parameters for customization
- Events for communication
3. **Handle state correctly:**
- Component state lives in component
- Shared state via services (DI)
- Persist state across prerender with `[PersistentState]`
4. **Validate in both environments** (for Auto mode)
## Component Patterns
### Basic Component
```razor
@* Counter.razor *@
<button @onclick="IncrementCount">
Clicked @count times
</button>
@code {
private int count = 0;
[Parameter]
public int InitialCount { get; set; } = 0;
protected override void OnInitialized()
{
count = InitialCount;
}
private void IncrementCount() => count++;
}
```
### Parameter and Event Callbacks
```razor
@* Parent.razor *@
<ChildComponent Value="@value" ValueChanged="@OnValueChanged" />
@* ChildComponent.razor *@
@code {
[Parameter] public string Value { get; set; } = "";
[Parameter] public EventCallback<string> ValueChanged { get; set; }
private async Task UpdateValue(string newValue)
{
await ValueChanged.InvokeAsync(newValue);
}
}
```
### State Persistence (.NET 8+)
```razor
@* Prevents double-fetch during prerender + hydration *@
@code {
[PersistentState]
public List<Product> Products { get; set; } = [];
protected override async Task OnInitializedAsync()
{
// Only fetches once, persisted across prerender
Products ??= await Http.GetFromJsonAsync<List<Product>>("api/products");
}
}
```
## Data Access Pattern for Auto Mode
```csharp
// Shared interface
public interface IProductService
{
Task<List<Product>> GetProductsAsync();
}
// Server implementation (direct DB access)
public class ServerProductService : IProductService
{
private readonly AppDbContext _db;
public async Task<List<Product>> GetProductsAsync()
=> await _db.Products.ToListAsync();
}
// Client implementation (HTTP call)
public class ClientProductService : IProductService
{
private readonly HttpClient _http;
public async Task<List<Product>> GetProductsAsync()
=> await _http.GetFromJsonAsync<List<Product>>("api/products");
}
// Registration
// Server: builder.Services.AddScoped<IProductService, ServerProductService>();
// Client: builder.Services.AddScoped<IProductService, ClientProductService>();
```
## Anti-Patterns to Avoid
| Anti-Pattern | Why It's Bad | Better Approach |
|--------------|--------------|-----------------|
| Large components | Hard to maintain, slow renders | Split into smaller components |
| Direct DB access in WASM | No DB in browser | Use HTTP API |
| Ignoring `ShouldRender` | Unnecessary re-renders | Override when needed |
| Sync JS interop in Server | Blocks SignalR circuit | Use `IJSRuntime` async |
| No error boundaries | One error crashes app | Use `<ErrorBoundary>` |
| Forgetting prerender state | Double API calls | Use `[PersistentState]` |
## Performance Best Practices
1. **Virtualize large lists:**
```razor
<Virtualize Items="@products" Context="product">
<ProductCard Product="@product" />
</Virtualize>
```
2. **Use `@key` for list diffing:**
```razor
@foreach (var item in items)
{
<ItemComponent @key="item.Id" Item="@item" />
}
```
3. **Debounce rapid events:**
```csharp
private Timer? _debounceTimer;
private void OnInput(ChangeEventArgs e)
{
_debounceTimer?.Dispose();
_debounceTimer = new Timer(_ => InvokeAsync(DoSearch), null, 300, Timeout.Infinite);
}
```
4. **Lazy load assemblies (WASM):**
```csharp
var assemblies = await LazyAssemblyLoader
.LoadAssembliesAsync(["MyHeavyFeature.wasm"]);
```
## JS Interop
### Calling JavaScript from C#
```csharp
@inject IJSRuntime JS
await JS.InvokeVoidAsync("alert", "Hello from Blazor!");
var result = await JS.InvokeAsync<string>("prompt", "Enter name:");
```
### Calling C# from JavaScript
```csharp
[JSInvokable]
public static string GetMessage() => "Hello from C#!";
```
```javascript
DotNet.invokeMethodAsync('MyAssembly', 'GetMessage')
.then(result => console.log(result));
```
## Deliver
- interactive Blazor components with appropriate render mode
- efficient state management and data flow
- proper handling of prerendering scenarios
- performant list rendering with virtualization
## Validate
- components render correctly in chosen mode
- state persists correctly across prerender/hydration
- no unnecessary re-renders (check with browser tools)
- JS interop works in both Server and WASM
- error boundaries catch component failures
- Auto mode works in both environments
章节与文件索引
按说明文件中的顺序排列。
触发
文档
参考文献
渲染模式 (.NET 8+)
工作流程
文件/命令 -> Static · InteractiveServer · InteractiveWebAssembly · InteractiveAuto · [PersistentState] · ShouldRender · IJSRuntime · <ErrorBoundary>
内容校验值 -> 5607d277cf09
当前原文的自动摘译,尚未人工审校。
触发
使用 C# 而不是 JavaScript 构建交互式 Web UI 在服务器、WebAssembly 或自动渲染模式之间进行选择 设计组件层次结构和状态管理 处理预渲染和水合作用 必要时与 JavaScript 集成
文档
Blazor 概述 渲染模式 性能最佳实践 状态管理 JS 互操作
参考文献
Patterns.md - 详细的组件模式、状态管理策略和 JS 互操作技术 anti-patterns.md - 常见的 Blazor 错误以及如何避免它们
渲染模式 (.NET 8+)
模式 · 运行位置 · 最适合
Static· 服务器(无交互性) · SEO 页面、营销内容InteractiveServer· 通过 SignalR 的服务器 · 实时应用程序、瘦客户端InteractiveWebAssembly· 通过 WASM 的浏览器 · 具有离线功能,客户端较多InteractiveAuto· 首先是服务器,然后是 WASM · 两全其美工作流程
根据需求选择渲染模式:需要 SEO?从静态或预渲染开始 需要实时?使用InteractiveServer 需要离线吗?使用 InteractiveWebAssembly 两者都想要吗?使用交互式自动