练习 - 添加组件

已完成

在本练习中,将 Razor 组件添加到应用的主页。

向主页添加 Counter 组件

  1. 打开 Components/Pages/Home.razor 文件。

  2. 通过在 Counter 文件的末尾添加 <Counter /> 元素,向页面添加 Home.razor 组件。

    @page "/"
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <Counter />
    
  3. 通过重启应用或使用热重载来应用更改。 组件 Counter 显示在主页上。

    主页上的“计数器”组件的屏幕截图。

修改组件

定义组件上的 Counter 参数,以指定每次单击按钮时递增多少。

  1. 使用 IncrementAmount 特性为 [Parameter] 添加公共属性。

  2. 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;
        }
    }
    
  3. Home.razor 中,更新 <Counter /> 元素来添加一个 IncrementAmount 属性,它会将增量更改为 10,如以下代码中的最后一行所示:

    @page "/"
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <Counter IncrementAmount="10" />
    
  4. 将更改应用到正在运行的应用。

    Home 组件现在有自己的计数器,每次选择“单击我”按钮时,计数器值都递增 10,如下图所示。

    显示计数器更新的主页的屏幕截图。

    /counterCounter 组件继续增加 1。