使用 Blazor 利用 ASP.NET Core 生成第一个 Web 应用

修改组件

组件参数使用特性或子内容指定,这允许在子组件上设置属性。在 Counter 组件上定义参数,以指定每次点击按钮时的增量:

  • 使用 [Parameter] 属性为 IncrementAmount 添加公共属性。
  • IncrementCount 方法更改为在递增 currentCount 值时使用 IncrementAmount

下面的代码演示了怎样实现此目的。突出显示的行显示更改。

Components/Pages/Counter.razor
@page "/counter"
@rendermode InteractiveServer

<PageTitle>Counter</PageTitle>

<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;
    }
}

Home.razor 中,更新 <Counter> 元素以添加 IncrementAmount 属性,该属性会将增量更改为 10,如以下代码中突出显示的行所示:

Components/Pages/Home.razor
@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<Counter IncrementAmount="10" />

通过单击“热重载”按钮将更改应用到应用程序。Home 组件现在具有自己的计数器,每次选择“单击我”按钮时,该计数器会递增 10,如下图所示。/counter 处的 Counter 组件(Counter.razor)将继续按 1 递增。

Home 组件现在具有自己的计数器,每次选择“单击我”按钮时,该计数器会递增 10,如下图所示。/counter 处的 Counter 组件(Counter.razor)将继续按 1 递增。

当前,主页包含以 10 递增的计数器,显示计数器为 40。

继续