























从组件参数设置交互模式时,如代码:
<Perrender Title="开启预呈现" @rendermode="new InteractiveServerRenderMode(true)">
<Perrender Title="开启预呈现" @rendermode="new InteractiveWebAssemblyRenderMode(true)">
@page "/prerendered-counter-2"
@implements IDisposable
@inject ILogger<PrerenderedCounter2> Logger
@inject PersistentComponentState ApplicationState
<PageTitle>Prerendered Counter 2</PageTitle>
<h1>Prerendered Counter 2</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount;
private PersistingComponentStateSubscription persistingSubscription;
protected override void OnInitialized()
{
persistingSubscription =
ApplicationState.RegisterOnPersisting(PersistCount);
if (!ApplicationState.TryTakeFromJson<int>(
nameof(currentCount), out var restoredCount))
{
currentCount = Random.Shared.Next(100);
Logger.LogInformation("currentCount set to {Count}", currentCount);
}
else
{
currentCount = restoredCount!;
Logger.LogInformation("currentCount restored to {Count}", currentCount);
}
}
private Task PersistCount()
{
ApplicationState.PersistAsJson(nameof(currentCount), currentCount);
return Task.CompletedTask;
}
void IDisposable.Dispose() => persistingSubscription.Dispose();
private void IncrementCount()
{
currentCount++;
}
}
blazor的组件就是一个类。我们也来尝试用C#类创建组件。
builder.OpenElement(0,"button");和builder.CloseElement();成对同时出现的方式创建一个html元素,其中第一个参数是该元素在整个组件中的索引键编码(用常量不要用变量),元素之间不可重复,第二个参数是指定html元素的类型builder.AddContent(10,ChildContent);来动态创建外部传进来的可渲染片断builder.AddAttribute(1,"class","btn btn-success");创建html元素属性;使用builder.AddAttribute(1,"onclick",()=>{});创建元素事件。namespace BlazorApp.Client.Components;
public class Button : ComponentBase
{
[Parameter] public RenderFragment? ChildContent{get;set;}
[Parameter] public bool Outline{get;set;}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenElement(0,"button");
//增加一个html元素属性
//builder.AddAttribute(1,"class","btn btn-success");
builder.AddAttribute(1,"class",$"btn btn-{(Outline?"outline-":"")}success");//以参数控制样式
builder.AddContent(10,ChildContent);
builder.CloseElement();
}
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。