ASP.NET?Core中的Blazor組件介紹
項(xiàng)目 Blazor 中,使用 .razor
結(jié)尾的文件,稱為組件;而 Blazor 中的組件,正式名稱是 razor 組件;
Blazor 組件是 razor 過渡而來的,使用 razor 的基本語法特性,但是 Balzor 不支持 razor 中的標(biāo)記幫助程序。
關(guān)于組件
.razor
文件分為頁面(帶@page
)和組件(不帶@page
,或者說頁面組件和非頁面組件。兩者區(qū)別在于頁面有路由,可以直接通過 URI 訪問,一般放在 Page 文件夾中;而組件,作為一個(gè)部件,必須嵌入其它組件中,在頁面中顯示,一般放到 Shared 文件夾中,供多個(gè)頁面共享、復(fù)用。
本文接下來所指的組件都是非頁面組件。.razor
文件中,開頭有 @page
標(biāo)記的,就是頁面組件,沒有的就是非頁面組件。
當(dāng)然兩者并沒有嚴(yán)格的區(qū)分。
組件命名時(shí),應(yīng)該帶上 Component
后綴。
組件類
每個(gè) .razor
文件,在編譯后會(huì)生成一個(gè)類,稱為組件類。 生成的類的名稱與文件名匹配。
因此,每個(gè) .razor
文件,必須以大寫字母開頭,按照類名命名規(guī)范定義文件名稱。
`.razor` ,以 `@code{}` 包含 C# 代碼,這部分代碼除了組件間可以使用,程序中也可以正常使用,因?yàn)閷儆陬惖囊徊糠帧?/p>
創(chuàng)建 Test.razor
文件,文件內(nèi)容如下:
@code{ public string Name { get; set; } }
Pargrom 中:
Pages.Test test = new Pages.Test(); test.Name = "Blazor";
簡單來說,就是可以作為一個(gè)類來使用。@code{}
中定義的成員,就是類的成員。
成員正常使用 public 、private 等訪問修飾符修飾。
靜態(tài)資產(chǎn)
默認(rèn)靜態(tài)資源文件位置在項(xiàng)目的 wwwroot 目錄,前端(.razor、.cshtml)等,默認(rèn)尋址時(shí),使用絕對(duì)路徑 /
即可訪問資源。
例如:
<img alt="Company logo" src="/images/logo.png" />
這個(gè)路徑是要放到前端才能,由前端訪問時(shí) ASP.NET Core 框架自動(dòng)處理,相當(dāng)于前端訪問 /
,后端訪問 D:/test/Blazor/wwwroot
。
路由與路由參數(shù)
頁面組件使用 @page
設(shè)置此頁面的訪問地址,這里沒有 Controller 和 Action 的分層和路由導(dǎo)航(相對(duì)地址),直接是一個(gè)絕對(duì)的訪問地址,并且全局唯一。
Index.razor
中,路由:
@page "/"
Blazor 不支持像 Controller 和 Action 那樣設(shè)置靈活的 URL 可選參數(shù)(URL Query),例如:
[HttpGet("Test/{Id}")] public string Test([FromQuery]int Id) { return "123"; }
Blazor 如果想通過 URL Query 傳遞參數(shù),可以使用 {
Name}
:
@page "/test" @page "/test/{Id}" <h2>@Id</h2> @code{ [Parameter] public string Id { get; set; } = "123"; }
因?yàn)?Blazor 不支持可選參數(shù),因此,如果只設(shè)置 @page "/test/{Id}"
,那么每次訪問都必須帶有這個(gè)參數(shù)值。
需要使用 [Parameter]
來修飾成員,才能捕獲 @page "/test/{Id}"
。
另外,理由參數(shù)是 string 類型,不能自動(dòng)轉(zhuǎn)為數(shù)值類型。不如會(huì)報(bào)錯(cuò):
InvalidOperationException: Unable to set property 'Id' on object of type 'BlazorApp1.Pages.Test'. The error was: Unable to cast object of type 'System.String' to type 'System.Int32'.
你可以接收后,顯式轉(zhuǎn)為數(shù)值類型。
組件參數(shù)
在 @code
代碼塊中,使用 [Parameter]
修飾的公共屬性,那么這個(gè)屬性就會(huì)標(biāo)識(shí)為組件指定參數(shù)。
注意官網(wǎng)文檔中,這個(gè)小節(jié)的代碼示例,實(shí)際是不允許這樣寫得的。
目前,有兩個(gè)地方需要使用 [Parameter]
特性,一個(gè)是前一小節(jié)的路由參數(shù)綁定,另一個(gè)是嵌入組件時(shí)使用。
示例:
Test.razor 文件內(nèi)容:
<h2>@Title</h2> @code{ [Parameter] public string Title { get; set; } = "test"; }
別的組件嵌入 Test.razor
這個(gè)組件時(shí),就可以使用 Title 傳遞參數(shù)進(jìn)去:
<Test Title="111" />
請(qǐng)勿創(chuàng)建會(huì)寫入其自己的組參數(shù)屬性的組件
前面我們說到, [Parameter]
特性的使用,這個(gè)特性時(shí)作為參數(shù)傳遞而使用的。
對(duì)于路由參數(shù),其修飾的屬性應(yīng)該是 privite
,對(duì)于其它組件傳遞參數(shù),屬性應(yīng)該設(shè)置為 public
。
如果一個(gè)組件的 @code{}
成員不需要被外界作為參數(shù)使用,就應(yīng)該設(shè)置為 private
。
因?yàn)?nbsp;.razor
一般不會(huì)作為類來使用。、;而且不設(shè)置 [Parameter]
的屬性,別的組件也使用不了這個(gè)屬性。
那么,文檔說 “請(qǐng)勿創(chuàng)建會(huì)寫入其自己的組參數(shù)屬性的組件”,指定是 [Parmeter]
休息的屬性,是作為參數(shù)傳遞使用的,不要在組件中修改這個(gè)屬性的值。
如果實(shí)在要操作的話,可以先拷貝這個(gè)值,使用別的變量操作,示例:
<h2>@Title</h2> @code{ [Parameter] public string Title { get; set; } = "test"; private string _Title; protected override void OnInitialized() { _Title = Title; } }
這樣,組件要操作的話,可以使用 _Title
,保留 Title
。OnInitalized()
是一個(gè)組件初始化的方法,也可以理解成構(gòu)造函數(shù),可以參考 https://docs.microsoft.com/zh-cn/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1#component-initialization-methods
子內(nèi)容
因?yàn)榻M件是可以嵌套的,可以要求另一個(gè)組件顯示要求的內(nèi)容。
- 被多個(gè)組件使用,不同組件要呈現(xiàn)不一樣的內(nèi)容;
- 要根據(jù)父組件的配置,顯示子組件;
- 組件 A 要求使用到的組件 B,顯示其傳遞的內(nèi)容;
簡單來說,就是將頁面內(nèi)容作為復(fù)雜類型傳遞給另一個(gè)組件,要求這個(gè)組件顯示出來。
那么,子內(nèi)容指的是一個(gè)組件可以接收另一個(gè)組件的內(nèi)容,使用 RenderFragment
來接收內(nèi)容。
示例如下:Test.razor
中,內(nèi)容:
<div>@Children</div> @code{ [Parameter] public RenderFragment Children { get; set; } }
另一個(gè)組件:
@page "/" <Test Children=r /> @code{ private RenderFragment r =@<h1>測試子內(nèi)容</h1>; }
RenderFragment
的使用,請(qǐng)自行查閱資料。
屬性展開
屬性展開是使用字典類型表示一個(gè) Html 標(biāo)簽的多個(gè)屬性。
<input id="1" maxlength="@Maxlength" placeholder="@Placeholder" required="@Required" size="@Size" /> <input id="2" @attributes="InputAttributes" /> @code { #region private string Maxlength { get; set; } = "10"; private string Placeholder { get; set; } = "Input placeholder text"; private string Required { get; set; } = "required"; private string Size { get; set; } = "50"; #endregion // 使用字典鍵值對(duì)表示 public Dictionary<string, object> InputAttributes { get; set; } = new Dictionary<string, object>() { { "maxlength", "10" }, { "placeholder", "Input placeholder text" }, { "required", "required" }, { "size", "50" } }; }
任意參數(shù)
[Paramter]
特性,只有一個(gè)屬性,其定義如下:
public bool CaptureUnmatchedValues { get; set; }
文檔說明:[Parameter] 上的 CaptureUnmatchedValues 屬性允許參數(shù)匹配所有不匹配任何其他參數(shù)的特性。
其作用是通過字典接收在父組件中出現(xiàn)但是未在 @code{}
中定義的參數(shù)屬性。
例如:Test.razor
中
@code{ // 這個(gè)屬性沒有用,隨便起個(gè)名字測試 [Parameter] public string A { get; set; } [Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; } }
父組件中使用:
<Test A="A" B="B" C="C" />
B、C 都是 Test.razor
中沒有出現(xiàn)過的,那么這些參數(shù)和參數(shù)值都會(huì)自動(dòng)轉(zhuǎn)為鍵值對(duì)存儲(chǔ)到 AdditionalAttributes 中。
測試示例:Test.razor
中的內(nèi)容
<ul> @foreach (var item in AdditionalAttributes) { <li>@item.Key - @item.Value</li> } </ul> @code{ // 這個(gè)屬性沒有用,隨便起個(gè)名字測試 [Parameter] public string TTT { get; set; } [Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object> AdditionalAttributes { get; set; } }
其它組件使用:
@page "/" <Test TTT="ces" id="useIndividualParams" maxlength="10" placeholder="Input placeholder text" required="required" size="50" />
捕獲對(duì)組件的引用
組件引用提供了一種引用組件實(shí)例的方法,使用 @ref
可以實(shí)現(xiàn)引用對(duì)參數(shù)的引用。
創(chuàng)建一個(gè) Test.razor
文件,內(nèi)容不限。
在一個(gè)組件中,引用該組件實(shí)例
@page "/" <Test @ref="_test" /> @code{ private Test _test; }
在使用 Test.razor
組件的同時(shí),保留了引用,以便在 @code{}
中使用其成員。
在外部調(diào)用組件方法以更新狀態(tài)
組件繼承了 ComponentBase 類型,有個(gè) InvokeAsync
方法可用于外界更新此 UI 的狀態(tài)。
示例如下:
創(chuàng)建 MyUIServer 類型,
// 能夠向所有正在打開的 Index.razor 頁面發(fā)送通知 public static class MyUIServer { // 向所有人發(fā)送通知 public static async Task ToMessage(string message) { if (events != null) { await events.Invoke(message); } } public static void AddEvent(Func<string, Task> func) { events += func; } public static void RemoveEvent(Func<string, Task> func) { events -= func; } private static event Func<string, Task> events; }
在 Index.razor
中
@page "/" @using BlazorApp1.Data @implements IDisposable <input @bind="_message" /> <button @onclick="Btn">發(fā)送消息</button> <ul> @foreach (var item in messageList) { <li>@item</li> } </ul> @code { private string _message; private List<string> messageList = new List<string>(); // 進(jìn)入頁面時(shí) protected override void OnInitialized() { MyUIServer.AddEvent(UIEvent); } // 退出當(dāng)前頁面UI后移除該事件 public void Dispose() { MyUIServer.RemoveEvent(UIEvent); } protected async Task UIEvent(string message) { // 組件自帶的方法,用于外部調(diào)用更新狀態(tài) await InvokeAsync(() => { messageList.Add(message); StateHasChanged(); }); } // 向所有正在訪問 Index.razor 頁面發(fā)送消息 private async Task Btn() { await MyUIServer.ToMessage(_message); } }
打開多個(gè)窗口,訪問頁面 https://localhost:5001/
,在其中一個(gè)窗口輸入內(nèi)容并且點(diǎn)擊按鈕,即可將消息內(nèi)容推送到其它窗口。
下面是一個(gè)修改官網(wǎng)示例的示例:
創(chuàng)建一個(gè)類型 NotifierService
public class NotifierService { public async Task Update(string key, int value) { if (Notify != null) { await Notify.Invoke(key, value); } } public event Func<string, int, Task> Notify; }
該類型的 Notify 可以綁定多個(gè)事件;通過調(diào)用 Update()
方法,可以觸發(fā)各個(gè)事件。
在 Startup 中注入服務(wù) services.AddSingleton<NotifierService>();
。Index.razor
中,內(nèi)容為:
@page "/" @using BlazorApp1.Data @inject NotifierService Notifier @implements IDisposable <p>Last update: @_lastNotification.key = @_lastNotification.value</p> @code { private (string key, int value) _lastNotification; protected override void OnInitialized() { Notifier.Notify += OnNotify; } public async Task OnNotify(string key, int value) { // 組件自帶的方法,用于外部調(diào)用更新狀態(tài) await InvokeAsync(() => { _lastNotification = (key, value); StateHasChanged(); }); } // 退出當(dāng)前頁面UI后移除該事件 public void Dispose() { Notifier.Notify -= OnNotify; } }
Test.razor
文件中:
@page "/test" @using BlazorApp1.Data @inject NotifierService Notifier Key: <input @bind="Key" /> Value: <input @bind="Value" /> <button @onclick="Update">更新</button> @code{ private string Key { get; set; } private int? Value { get; set; } private async Task Update() { await Notifier.Update(Key, Value.Value); Key = string.Empty; Value = null; } }
然后啟動(dòng)項(xiàng)目,一個(gè)頁面打開 https://localhost:5001/
,另一個(gè)頁面打開 https://localhost:5001/test
。
在 test
頁面輸入 Key 和 Value,點(diǎn)擊按鈕,即可通知到所有正在打開 Index.razor
的頁面。
使用 @ 鍵控制是否保留元素和組件
在使用表格或了表等元素時(shí),如果出現(xiàn)插入或刪除、更新等情況,整個(gè)表格或列表,就會(huì)被重新渲染。這樣會(huì)帶來比較大的性能消耗。
一般使用綁定的元素,其更新是自動(dòng)的,不需要人為控制。
在能保證每一項(xiàng)的某個(gè)元素列,都是唯一的時(shí)候,我們可以使用 @key
關(guān)鍵字來優(yōu)化組件。
示例:
@page "/" @using BlazorApp1.Data Key: <input @bind="_key" /> Value: <input @bind="_value" /> <button @onclick="Add">添加</button> <button @onclick="Remove">移除</button> <ul> @foreach (var item in dic) { <li @key="item.Key">@item.Key - @item.Value</li> } </ul> @code { private int? _key; private int _value; private List<MyData> dic { get; set; } = new List<MyData>(); private void Add() { if (_key == null) return; dic.Add(new MyData { Key = _key.Value, Value = _value }); _key = null; } private void Remove() { if (_key == null) return; dic.Remove(dic.First(x => x.Key == _key.Value)); _key = null; } }
指定基類
@inherits
指令可用于指定組件的基類。 組件都默認(rèn)繼承了 ComponentBase 。
示例:
創(chuàng)建文件 TestBase.razor
,內(nèi)容如下
@code{ protected int Id { get; set; } }
創(chuàng)建 Test.razor
,文件內(nèi)容如下
@inherits TestBase @code{ public int Get() { return Id; } }
指定屬性
可以通過 @attribute 指令在 Razor 組件中指定組件的特性(屬性)。 例如頁面需要登錄才能訪問,則添加 [Authorize]
。
@page "/" @attribute [Authorize]
導(dǎo)入組件
當(dāng)要使用的組件與當(dāng)前組件在同一個(gè)命名空間時(shí),不需要“導(dǎo)入”,如果兩者不在同一個(gè)命名空間,則可以使用 @using
導(dǎo)入此組件。
原始 HTML
使用 MarkupString 類型可以將字符串轉(zhuǎn)為 HTML 元素對(duì)象。
@html @code{ public MarkupString html = (MarkupString)"<h1> Test </h1>"; }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解ABP框架中的數(shù)據(jù)過濾器與數(shù)據(jù)傳輸對(duì)象的使用
ABP框架是一個(gè)基于ASP.NET的Web開發(fā)框架,這里我們來詳解ABP框架中的數(shù)據(jù)過濾器與數(shù)據(jù)傳輸對(duì)象的使用,需要的朋友可以參考下2016-06-06ASP.NET 中 Button、LinkButton和ImageButton 三種控件的使用詳解
本文主要介紹Button、LinkButton和ImageButton 三種控件的使用方法,并一一舉例演示它們的用法,希望對(duì)大家有所幫助。2016-04-04詳解ABP框架的參數(shù)有效性驗(yàn)證和權(quán)限驗(yàn)證
ABP框架是基于ASP.NET的Web開發(fā)框架(GitHub: https://github.com/aspnetboilerplate),在ASP.NET框架之上又添加了更強(qiáng)大的功能,這里我們就來詳解ABP框架的參數(shù)有效性驗(yàn)證和權(quán)限驗(yàn)證2016-06-06FileStreaReder和StreamReader兩個(gè)類介紹
由于最近需要對(duì)文件進(jìn)行處理,所以看了一下MSDN的System.IO讀取文件的兩個(gè)類。下面對(duì)兩個(gè)類簡單的整理一下2012-04-04