在此练习中,将 Razor 组件添加到应用程序的主页。
在 Visual Studio Code 中,打开包含在模块 3 中创建的 BlazorApp 项目的文件夹。
向主页添加 Counter 组件
在 Visual Studio Code 项目资源管理器中展开文件夹。
选择“页面”以查看现有 Razor 页面。
选择 Index.razor 文件将其打开。
通过在 Index.razor
文件的末尾添加 <Counter />
元素,向页面添加 Counter
组件。
@page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
<Counter />
保存文件,在上一模块中执行的 dotnet watch run
命令将重启应用,然后将其刷新到浏览器中,以便 Counter
组件显示在主页上。

修改组件
组件参数使用特性或子内容指定,允许在子组件上设置属性。 在 Counter 组件上定义一个参数,用于指定每次单击按钮时递增的量:
- 使用
[Parameter]
特性为IncrementAmount
添加公共属性。 - 更改
IncrementCount
方法以在currentCount
的值递增时使用IncrementAmount
。
Counter.razor 文件中的以下代码演示如何实现这一点。
@page "/counter"
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
[Parameter]
public int IncrementAmount { get; set; } = 1;
private void IncrementCount()
{
currentCount += IncrementAmount;
}
}
在 Index.razor
中,更新 <Counter>
元素来添加一个 IncrementAmount
属性,它会将增量更改为 10,如以下代码中的最后一行所示:
@page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
<Counter IncrementAmount="10" />
Index
组件现在有自己的计数器,每次选择“单击我”按钮时,计数器值都递增 10,如下图所示。 /counter
处 Counter
组件 (Counter.razor
) 的值继续递增 1。
