练习 - 添加组件

已完成

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

向主页添加 Counter 组件

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

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

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

    Screenshot of the Counter component on the Home page.

修改组件

Counter 组件上定义一个参数,用于指定每次单击按钮时递增的量。

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

  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,如下图所示。

    Screenshot of the Home page with the Counter update.

    /counterCounter 组件继续增加 1。