练习 - 添加组件
在此练习中,将 Razor 组件添加到应用的主页。
向主页添加 Counter 组件
打开 Components/Pages/Home.razor 文件。
通过在
Home.razor
文件的末尾添加<Counter />
元素,向页面添加Counter
组件。@page "/" <PageTitle>Home</PageTitle> <h1>Hello, world!</h1> Welcome to your new app. <Counter />
通过重启应用或使用热重载来应用更改。
Counter
组件显示在主页上。
修改组件
在 Counter
组件上定义一个参数,用于指定每次单击按钮时递增的量。
使用
[Parameter]
特性为IncrementAmount
添加公共属性。更改
IncrementCount
方法以在currentCount
的值递增时使用IncrementAmount
值。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,如以下代码中的最后一行所示:@page "/" <h1>Hello, world!</h1> Welcome to your new app. <Counter IncrementAmount="10" />
将更改应用到正在运行的应用。
Home
组件现在有自己的计数器,每次选择“单击我”按钮时,计数器值都递增 10,如下图所示。/counter
的Counter
组件继续增加 1。