練習:新增元件

已完成

在此練習中,您會將 Razor 元件新增至應用程式的首頁。

將計數器元件新增至首頁

  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 元件會繼續遞增一。