ASP.NET Core Blazor Webassembly 之 組件

来源:https://www.cnblogs.com/kklldog/archive/2020/05/27/blazor-webassembly-component.html
-Advertisement-
Play Games

關於組件 現在前端幾大輪子全面組件化。組件讓我們可以對常用的功能進行封裝,以便復用。組件這東西對於搞.NET的同學其實並不陌生,以前ASP.NET WebForm的用戶控制項其實也是一種組件。它封裝html代碼,封裝業務邏輯,對外提供屬性事件等信息,它完完全全就是個組件,只是用戶控制項跑在服務端,而現在 ...


關於組件

現在前端幾大輪子全面組件化。組件讓我們可以對常用的功能進行封裝,以便復用。組件這東西對於搞.NET的同學其實並不陌生,以前ASP.NET WebForm的用戶控制項其實也是一種組件。它封裝html代碼,封裝業務邏輯,對外提供屬性事件等信息,它完完全全就是個組件,只是用戶控制項跑在服務端,而現在的組件大多數直接跑在前端。現在Blazor Webassembly微軟正式把組件帶到前端,讓我們看看它是怎麼玩的。

第一個組件

廢話不多說下麵開始構建第一個組件。這個組件很簡單就是綠色的面板加一個標題的容器,我們就叫它GreenPanel吧。

新建Blazor Webassembly項目

前幾天的build大會,Blazor Webassembly已經正式release了。我們更新最新版的Core SDK就會安裝正式版的模板。
tCTG2F.md.png
新建項目選Blazor Webassembly App項目模板

新建GreenPanel組件

在pages命令下新建一個文件夾叫做components,在文件夾下新建一個razor組件,命名為GreenPanel.razor。

註意:組件的命名必須大寫字母開頭

tCTubn.md.png
添加代碼如下:

<div class="green-panel">
    <div class="title">
        Green panel
    </div>
    <div class="content">
    </div>
</div>

<style>
    .green-panel{
        background-color: green;
        height:400px;
        width:400px;
    }
    .green-panel .title {
        border-bottom:1px solid #333;
        height:30px;
    }
    .green-panel .content {
    }
</style>

@code { override void OnInitialized()
        {
            base.OnInitialized();
        }
}

一個組件主要是由html,style ,code等組成。html,style用來控制ui表現層,code用來封裝邏輯。

註意:Blazor目前沒有樣式隔離技術,所以寫在組件內的style有可能會影響其他html元素

使用組件

使用組件跟其他框架大體是相同的,直接在需要使用的地方使用以我們組件名作為一個html元素插入:
如果不在同一層目錄下,則需要導入命名空間。在_Imports.razor文件內引用組件的命名空間:

...
@using BlazorWasmComponent.Components

在index頁面使用組件:

<GreenPanel></GreenPanel>

運行一下:
tCbQUI.md.png

組件類

每個組件最後都會編譯成一個C#類,讓我們用ILSPy看看一眼長啥樣:

// BlazorWasmComponent.Components.GreenPanel
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;

public class GreenPanel : ComponentBase
{
	protected override void BuildRenderTree(RenderTreeBuilder __builder)
	{
		__builder.AddMarkupContent(0, "<div class=\"green-panel\">\r\n    <div class=\"title\">\r\n        Green panel\r\n    </div>\r\n    <div class=\"content\">\r\n    </div>\r\n</div>\r\n\r\n");
		__builder.AddMarkupContent(1, "<style>\r\n    .green-panel{\r\n        background-color: green;\r\n        height:400px;\r\n        width:400px;\r\n    }\r\n    .green-panel .title {\r\n        border-bottom:1px solid #333;\r\n        height:30px;\r\n    }\r\n    .green-panel .content {\r\n    }\r\n</style>");
	}

	protected override void OnInitialized()
	{
		base.OnInitialized();
	}
}

GreenPanel組件會編譯成一個GreenPanel類,繼承自ComponentBase基類。裡面有幾個方法:

  1. BuildRenderTree 用來構建html,css等ui元素
  2. 其它code部分會也會被合併到這個類裡面

生命周期

瞭解組件聲明周期對我們使用組件有很大的幫助。一個組件的聲周期主要依次以下幾個階段:

  1. OnInitialized、OnInitializedAsync
  2. OnParametersSet、OnParametersSetAsync
  3. OnAfterRender、OnAfterRenderAsync
  4. Dispose

如果要在每個生命階段插入特定的邏輯,請重寫這些方法:

@implements IDisposable

@code {
    protected override void OnInitialized()
    {
        Console.WriteLine("OnInitialized");
        base.OnInitialized();
    }
    protected override Task OnInitializedAsync()
    {
        Console.WriteLine("OnInitializedAsync");
        return base.OnInitializedAsync();
    }
    protected override void OnParametersSet()
    {
        Console.WriteLine("OnParametersSet");
        base.OnParametersSet();
    }
    protected override Task OnParametersSetAsync()
    {
        Console.WriteLine("OnParametersSetAsync");

        return base.OnParametersSetAsync();
    }
    protected override void OnAfterRender(bool firstRender)
    {
        Console.WriteLine("OnAfterRender");
        base.OnAfterRender(firstRender);
    }
    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        Console.WriteLine("OnAfterRenderAsync");
        return base.OnAfterRenderAsync(firstRender);
    }

    public void Dispose()
    {
        Console.WriteLine("Dispose");
    }
}

註意:組件預設並不繼承IDisposable介面,如果要重寫Dispose方法請手工使用@implements方法繼承介面IDisposable

運行一下,並且切換一下頁面,使組件銷毀,可以看到所有生命周期方法依次執行:
tCO5in.md.png

組件屬性

我們定義組件總是免不了跟外部進行交互,比如從父組件接受參數,或者把自身的數據對外暴露。我們可以使用[Parameter]來定義一個組件的屬性。這裡叫做Parameter,估計是為了跟C#里的屬性(property,attribute)進行區分。
對我們的GreenPanel組件進行改進,支持從外部定義標題的內容:

<div class="green-panel">
    <div class="title">
        @Title
    </div>
    <div class="content">
    </div>
</div>

<style>
    .green-panel {
        background-color: green;
        height: 400px;
        width: 400px;
    }

        .green-panel .title {
            border-bottom: 1px solid #333;
            height: 30px;
        }

        .green-panel .content {
        }
</style>

@code {

    [Parameter]
    public string Title { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();
    }

}

在父組件使用:

@page "/"

<GreenPanel Title="Panel A"></GreenPanel>

運行一下:
tFRHvd.png

上面傳遞的是簡單類型String,下麵讓我們試試傳遞複雜類型的數據進去。我們繼續對GreenPanel改造。改造成ColorPanel,它接受一個Setting對象來設置標題跟背景顏色。
定義Setting類:

  public class PanelSetting
    {
        public string Title { get; set; }

        public string BgColor { get; set; }
    }

定義ColorPanel:

<div class="green-panel">
    <div class="title">
        @Setting.Title
    </div>
    <div class="content">
    </div>
</div>

<style>
    .green-panel {
        background-color: @Setting.BgColor;
        height: 400px;
        width: 400px;
    }

        .green-panel .title {
            border-bottom: 1px solid #333;
            height: 30px;
        }

        .green-panel .content {
        }
</style>

@using BlazorWasmComponent.models;
@code {

    [Parameter]
    public PanelSetting Setting { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();
    }

}

在父組件使用:

@page "/"

<p>@PanelSetting.Title</p>
<p>@PanelSetting.BgColor</p>

<ColorPanel Setting="PanelSetting"></ColorPanel>

@using BlazorWasmComponent.models;
@code{  

    public PanelSetting PanelSetting { get; set; }

    protected override void OnInitialized()
    {
        PanelSetting = new PanelSetting
        {
            BgColor = "Red",
            Title = "Panel RED"
        };

        base.OnInitialized();
    }
}

運行一下:
tFhaDA.png

註意:上一篇WebAssembly初探里有個錯誤,當時認為這個屬性是單向數據流,經過試驗子組件對父組件傳入的數據源進行修改的時候其實是會反應到父組件的,只是如果你使用@符號綁定數據的時候並不會像angularjs,vue等立馬進行刷新。關於這個事情感覺可以單獨寫一篇,這裡就不細說了。

組件事件

我們的組件當然也可以提供事件,已供外部訂閱,然後從內部激發來通知外部完成業務邏輯,實現類似觀察者模式。繼續改造ColorPanel,當點擊時候對外拋出事件。
使用EventCallback、EventCallback< T > 來定義事件:

<div class="green-panel" @onclick="DoClick">
    <div class="title">
        @Setting.Title
    </div>
    <div class="content">
    </div>
</div>

<style>
    .green-panel {
        background-color: @Setting.BgColor;
        height: 400px;
        width: 400px;
    }

        .green-panel .title {
            border-bottom: 1px solid #333;
            height: 30px;
        }

        .green-panel .content {
        }
</style>

@using BlazorWasmComponent.models;
@code {

    [Parameter]
    public PanelSetting Setting { get; set; }
    [Parameter]
    public EventCallback OnClick { get; set; }

    protected override void OnInitialized()
    {

        base.OnInitialized();
    }

    public void DoClick()
    {
        OnClick.InvokeAsync(null);
    }
}


父組件訂閱事件:

@page "/"

<p>
    子組件點擊次數:@ClickCount
</p>
<ColorPanel Setting="PanelSetting" OnClick="HandleClick"></ColorPanel>

@using BlazorWasmComponent.models;
@code{  

    public PanelSetting PanelSetting { get; set; }

    public int ClickCount { get; set; }

    protected override void OnInitialized()
    {
        PanelSetting = new PanelSetting
        {
            BgColor = "Red",
            Title = "Panel RED"
        };

        base.OnInitialized();
    }

    private void HandleClick()
    {
        ClickCount++;
    }
}

運行一下,並點擊子組件,父組件的計數器會被+1:
tFTkSf.png

子內容

當我們定義容器級別的組件時往往需要往組件內傳遞子內容。比如我們的ColorPanel明顯就有這種需求,這個Panel內部會被放上其它元素或者其它組件,這個時候我們可以使用ChildContent屬性來實現。

<div class="green-panel" @onclick="DoClick">
    <div class="title">
        @Setting.Title
    </div>
    <div class="content">
        @ChildContent
    </div>
</div>

<style>
    .green-panel {
        background-color: @Setting.BgColor;
        height: 400px;
        width: 400px;
    }

        .green-panel .title {
            border-bottom: 1px solid #333;
            height: 30px;
        }

        .green-panel .content {
        }
</style>

@using BlazorWasmComponent.models;
@code {

    [Parameter]
    public PanelSetting Setting { get; set; }
    [Parameter]
    public EventCallback OnClick { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    protected override void OnInitialized()
    {

        base.OnInitialized();
    }

    public void DoClick()
    {
        OnClick.InvokeAsync(null);
    }
}

定義一個類型為RenderFragment名稱為ChildContent的屬性,然後在html內使用@ChildContent來指代它。這樣子內容就會被替換到指定的位置。
父組件使用,我們給ColorPanel的內部設置一個文本框吧:

@page "/"

<p>
    子組件點擊次數:@ClickCount
</p>
<ColorPanel Setting="PanelSetting" OnClick="HandleClick">

   輸入框: <input />

</ColorPanel>

@using BlazorWasmComponent.models;
@code{  

    public PanelSetting PanelSetting { get; set; }

    public int ClickCount { get; set; }

    protected override void OnInitialized()
    {
        PanelSetting = new PanelSetting
        {
            BgColor = "Red",
            Title = "Panel RED"
        };

        base.OnInitialized();
    }

    private void HandleClick()
    {
        ClickCount++;
    }
}

運行一下看看我們的文本框會不會出現在panel內部:
tF7tv8.png

@ref

因為我們的組件使用是在html內,當你在@code內想要直接通過代碼操作子組件的時候可以給子組件設置@ref屬性來直接獲取到子組件的對象。繼續改造ColorPanel,在它初始化的時候生產一個ID。

<div class="green-panel" @onclick="DoClick">
    <div class="title">
        @Setting.Title
    </div>
    <div class="content">
        @ChildContent
    </div>
</div>

<style>
    .green-panel {
        background-color: @Setting.BgColor;
        height: 400px;
        width: 400px;
    }

        .green-panel .title {
            border-bottom: 1px solid #333;
            height: 30px;
        }

        .green-panel .content {
        }
</style>

@using BlazorWasmComponent.models;
@code {

    public string ID { get; set; }

    [Parameter]
    public PanelSetting Setting { get; set; }
    [Parameter]
    public EventCallback OnClick { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    protected override void OnInitialized()
    {
        ID = Guid.NewGuid().ToString();
        base.OnInitialized();
    }

    public void DoClick()
    {
        OnClick.InvokeAsync(null);
    }
}

修改父組件,添加一個按鈕,當點擊的時候直接獲取子組件的Id:

@page "/"

<p>
    子組件ID:@subId
</p>
<ColorPanel Setting="PanelSetting" OnClick="HandleClick" @ref="colorPanel">
   輸入框: <input />
</ColorPanel>
<button @onclick="GetSubComponentId" class="btn btn-info">獲取子組件ID</button>

@using BlazorWasmComponent.models;
@code{  

    private string subId;

    private ColorPanel colorPanel;

    public PanelSetting PanelSetting { get; set; }

    public int ClickCount { get; set; }

    protected override void OnInitialized()
    {
        PanelSetting = new PanelSetting
        {
            BgColor = "Red",
            Title = "Panel RED"
        };

        base.OnInitialized();
    }

    private void HandleClick()
    {
        ClickCount++;
    }

    private void GetSubComponentId ()
    {
        this.subId = colorPanel.ID;
    }
}

運行一下:
tFLFsK.png

@key

當使用迴圈渲染組件的時候請在組件上使用@key來加速Blazor的diff演算法。有了key就可以快速的區分哪些組件是可以復用的,哪些是要新增或刪除的,特別是在對迴圈列表插入對象或者刪除對象的時候特別有用。如果使用過vue就應該很容易明白有了key可以降低虛擬dom演算法的複雜度,在這裡猜測blazor內部應該也是類似的演算法。

@page "/"


@foreach (var key in List)
{
    <ColorPanel @key="key" Setting="PanelSetting"></ColorPanel>
}

@using BlazorWasmComponent.models;
@code{  

    public List<String> List = new List<string>
    {
        Guid.NewGuid().ToString(),
         Guid.NewGuid().ToString(),
          Guid.NewGuid().ToString()
    };

    public PanelSetting PanelSetting { get; set; }


    protected override void OnInitialized()
    {
        PanelSetting = new PanelSetting
        {
            BgColor = "Red",
            Title = "Panel RED"
        };

        base.OnInitialized();
    }

}

太晚了就這樣吧,喜歡的話請點個贊,謝謝!

相關內容:
ASP.NET Core Blazor 初探之 Blazor WebAssembly
ASP.NET Core Blazor 初探之 Blazor Server


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 8.數據嵌套 在Python中,各種數據是可以相互嵌套的,如列表中嵌套元組、整型、字典等,字典中也可以嵌套元組、列表等,甚至可以嵌套自身。使用起來非常靈活。這種嵌套可以在實際項目中靈活運用各種數據類型進行嵌套。示例如下所示: a=[ 1, 23.45, "name", ("name","age"), ...
  • 一個經典的程式猿名言是:”如果只能有一種數據結構,那就用哈希表吧。“ ...
  • 7.集合 集合的主要特性如下所示: 1.集合中不會存在重覆元素,天生自帶去重功能 2.集合可使用{item1,item2,...itemn}或set()進行定義,如果要定義一個空的集合,必須使用set()函數 3.使用set()函數定義集合時,裡面的參數必須為列表或元組 4.集合是無序的 7.1 常 ...
  • 6.37(格式化整數)使用下麵的方法頭編寫一個方法,用於將整數格式化為指定寬度: public static String format(int number, int width) 方法為數字number返回一個帶有一個或多個以0作為首碼的字元串。字元串的位數就是寬度。比如,format(34,4 ...
  • 天下武功,唯快不破,雖然支持C/C++ 開發工具(俗稱:IDE)有很多,但是在團隊項目開發中使用最多的還是Visual Studio(簡稱VS),好用而且功能強大,畢竟親爸爸是微軟! 現在Visual Studio 已經更新到VS2019,VS 支持開發人員編寫跨平臺的應用程式,從 Windows ...
  • akka 2.6.x正式發佈以來已經有好一段時間了。核心變化是typed-actor的正式啟用,當然persistence,cluster等模塊也有較大變化。一開始從名稱估摸就是把傳統any類型的消息改成強類型消息,所以想拖一段時間看看到底能對我們現有基於akka-classic的應用軟體有什麼深層 ...
  • 由於開發中發現以前的Activex控制項功能不夠用,沒辦法需要下載源碼重新增加功能。。。。 這個項目最開始也不我寫的,而我也是個小白,花了半天改好了代碼,然後打包用了一天半。-0- 各種百度,各種找。。。。準備用 InstallShield 2015打包,結果怎麼下打包好了就提示啥啥啥試用版。。。。最 ...
  • 格式轉換convert:轉換圖像的模式transpose:轉換圖像的格式convert之前已經使用過了,這裡就簡單演示一下transpose的作用,transpose主要傳入一些Image中的常量: from PIL import Image# 打開圖像im = Image.open('nnz.jp ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...