练习 - 添加组件
在本练习中,将 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 参数,以指定每次单击按钮时递增多少。
为
IncrementAmount添加具有[Parameter]特性的公共属性。将
IncrementCount方法更改为在递增IncrementAmount的值时使用currentCount的值。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。