第三章 组件(11)- 动态组件与表格组件
DynamicComponent组件
在 Blazor 中,<DynamicComponent>
组件允许在运行时动态地加载和渲染组件。
- 主要是通过
<DynamicComponent>
组件的组件参数Type
来设置要渲染的组件
在下面的示例中,DynamicComponentTest组件通过选择下拉框来动态渲染组件ComponentA或ComponentB
-
ComponentA.razor
<h3>这里是A组件</h3>
-
ComponentB.razor
<h3>这里是B组件</h3>
-
DynamicComponentTest.razor
@page "/dynamic-test" @using System.ComponentModel <PageTitle>动态组件测试</PageTitle> <select @onchange="OnSelectChanged"> <option value="">选择组件</option> @foreach (var key in _selects.Keys) { <option value="@key">@key</option> } </select> @if (_componentType != null) { <div> <DynamicComponent Type="_componentType"/> </div> } @code { private Type? _componentType; private Dictionary<string, Type> _selects = new() { {"组件A",typeof(ComponentA)}, {"组件B",typeof(ComponentB)} }; private void OnSelectChanged(ChangeEventArgs args) { if ((args.Value is string selectValue) && !String.IsNullOrWhiteSpace(selectValue)) { _componentType = _selects[selectValue]; } else { _componentType = null; } } }
一、传递参数
在 Blazor 框架中,当使用<DynamicComponent>
动态组件渲染其它组件内容时,若其它组件具有组件参数,则需要在动态组件的组件参数Parameters
传入IDictionary<string, object>
类型的字典数据,组件的参数名和参数值就以 key/value 的形式存放在字典中。当<DynamicComponent>
访问的组件中带有参数,且与IDictionary<string, object>
字典中的参数名匹配,则就会应用上该字典中的参数。
-
ComponentA.razor
<h3>这里是A组件</h3> <p> 数据:@Data </p> <p> 数字:@Number </p> @code { [Parameter] public string? Data { get; set; } [Parameter] public int Number { get; set; } }
-
ComponentB.razor
<h3>这里是B组件</h3> <p> 数据:@Data </p> <p> 数字:@Number </p> @code { [Parameter] public string? Data { get; set; } [Parameter] public int Number { get; set; } }
-
DynamicComponentTest.razor
@page "/dynamic-test" @using System.ComponentModel <PageTitle>动态组件测试</PageTitle> <select @onchange="OnSelectChanged"> <option value="">选择组件</option> @foreach (var key in _selects.Keys) { <option value="@key">@key</option> } </select> @if (_componentType != null) { <div> <DynamicComponent Type="_componentType" Parameters="paramDic" /> </div> } @code { private Type? _componentType; private Dictionary<string, Type> _selects = new() { {"组件A",typeof(ComponentA)}, {"组件B",typeof(ComponentB)} }; //存储参数的字典 IDictionary<string, object> paramDic = new Dictionary<string, object>() { ["Data"] = "Schuyler", ["Number"] = 22 }; private void OnSelectChanged(ChangeEventArgs args) { if ((args.Value is string selectValue) && !String.IsNullOrWhiteSpace(selectValue)) { _componentType = _selects[selectValue]; } else { _componentType = null; } } }
尝试后发现,在<DynamicComponent>
组件中传递字典时,如果渲染的组件缺少对应的组件参数,会抛出异常;但是若在渲染的组件定义了参数,而传入<DynamicComponent>
组件的字典中没有对应的参数,是不会引发异常的。
二、回调事件
如果动态组件中,需要使用到回调事件,也可以通过IDictionary<string, object>
作为参数传入 DynamicComponent
组件。
-
ComponentMetadata.cs
public class ComponentMetadata { public required Type Type { get; init; } public required string Name { get; init; } public Dictionary<string, object> Parameters { get; } = []; }
-
RocketLab2.razor
<h2>Rocket Lab®</h2> <p> Rocket Lab is a registered trademark of <a href="https://www.rocketlabusa.com/">Rocket Lab USA Inc.</a> </p> <button @onclick="OnClickCallback"> Trigger a Parent component method </button> @code { [Parameter] public EventCallback<MouseEventArgs> OnClickCallback { get; set; } }
-
SpaceX2.razor
<h2>SpaceX®</h2> <p> SpaceX is a registered trademark of <a href="https://www.spacex.com/">Space Exploration Technologies Corp.</a> </p> <button @onclick="OnClickCallback"> Trigger a Parent component method </button> @code { [Parameter] public EventCallback<MouseEventArgs> OnClickCallback { get; set; } }
-
UnitedLaunchAlliance2.razor
<h2>United Launch Alliance®</h2> <p> United Launch Alliance and ULA are registered trademarks of <a href="https://www.ulalaunch.com/">United Launch Alliance, LLC</a>. </p> <button @onclick="OnClickCallback"> Trigger a Parent component method </button> @code { [Parameter] public EventCallback<MouseEventArgs> OnClickCallback { get; set; } }
-
VirginGalactic2.razor
<h2>Virgin Galactic®</h2> <p> Virgin Galactic is a registered trademark of <a href="https://www.virgingalactic.com/">Galactic Enterprises, LLC</a>. </p> <button @onclick="OnClickCallback"> Trigger a Parent component method </button> @code { [Parameter] public EventCallback<MouseEventArgs> OnClickCallback { get; set; } }
-
MyDynamicComponent3.razor
@page "/dynamic-component-3" @rendermode InteractiveServer <PageTitle>Dynamic Component 3</PageTitle> <h1>Dynamic Component Example 3</h1> <p> <label> Select your transport: <select @onchange="OnDropdownChange"> <option value="">Select a value</option> @foreach (var c in Components) { <option value="@c.Key">@c.Value.Name</option> } </select> </label> </p> @if (selectedComponent is not null) { <div class="border border-primary my-1 p-1"> <DynamicComponent Type="selectedComponent.Type" Parameters="selectedComponent.Parameters" /> </div> } <p> @message </p> @code { private ComponentMetadata? selectedComponent; private string? message; private Dictionary<string, ComponentMetadata> Components => new() { [nameof(RocketLab2)] = new ComponentMetadata() { Type = typeof(RocketLab2), Name = "Rocket Lab", Parameters = { [nameof(RocketLab2.OnClickCallback)] = EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) } }, [nameof(VirginGalactic2)] = new ComponentMetadata() { Type = typeof(VirginGalactic2), Name = "Virgin Galactic", Parameters = { [nameof(VirginGalactic2.OnClickCallback)] = EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) } }, [nameof(UnitedLaunchAlliance2)] = new ComponentMetadata() { Type = typeof(UnitedLaunchAlliance2), Name = "ULA", Parameters = { [nameof(UnitedLaunchAlliance2.OnClickCallback)] = EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) } }, [nameof(SpaceX2)] = new ComponentMetadata() { Type = typeof(SpaceX2), Name = "SpaceX", Parameters = { [nameof(SpaceX2.OnClickCallback)] = EventCallback.Factory.Create<MouseEventArgs>(this, ShowDTMessage) } } }; private void OnDropdownChange(ChangeEventArgs e) { if ((e.Value is string dropdownValue) && !String.IsNullOrWhiteSpace(dropdownValue)) { selectedComponent = Components[dropdownValue]; } else { selectedComponent = null; } } private void ShowDTMessage(MouseEventArgs e) => message = $"The current DT is: {DateTime.Now}."; }
避免 catch-all 参数
避免使用路由的 catch-all
参数。 如果使用了 catch-all
参数,则 DynamicComponent
上的每个显式参数都会成为无法传递给动态子级的保留字。 传递给 DynamicComponent
的任何新参数都是中断性变更,因为它们会开始隐藏恰好同名的子组件参数。 调用方不太可能始终了解要传递给所有可能的动态子级的一组固定的参数名称。
QuickGrid 组件
QuickGrid
组件是Razor内置组件,用于以表格格式快速高效地显示数据。
- PS:官网上说明,没有对
QuickGrid
进行扩展的计划,并建议使用第三方提供的表格组件
使用QuickGrid
组件之前,需要先从Nuget中下载扩展包:
常用属性
Items
:设置表格的数据源集合,类型是可以为 null
的 IQueryable<T>
,其中 T
是网格中每一行表示的数据类型。
ItemsProvider
:设置表格数据源的提供方法。
Class
:可选的 CSS 类名称。 如果已提供,则类名称将包含在渲染的表的 class
属性中。
Theme
:主题名称(默认值:default
), 这会影响样式规则与表匹配。
Virtualize
:如果为 true
,则网格会使用虚拟化呈现。 这通常与滚动结合使用,导致网格仅提取和渲染当前滚动视区周围的数据。
- 如果使用
Virtualize
,则应为ItemSize
提供值,并且必须确保每一行以恒定的高度渲染。 - 一般情况下,如果渲染的数据量较小或使用的是分页,最好不要使用
Virtualize
。
ItemSize
:仅当使用 Virtualize
时才适用。 ItemSize
定义每一行的预期高度(以像素为单位),使虚拟化机制能够提取正确数量的项,以匹配显示大小并确保准确滚动。
ItemKey
:(可选)在渲染的每一行上为 @key
定义值。用于为每个数据项指定唯一标识符,例如主键值。 这样,网格就可以根据唯一标识符保留行元素和数据项之间的关联,即使 T
实例被新副本替换(例如,在对基础数据存储执行新查询之后)也是如此。 如果未设置,则 @key
为 T
实例。
Pagination
:(可选)将此 T
实例与 PaginationState
模型链接,使网格仅提取并渲染数据的当前页。 这通常与 Paginator
组件或显示和更新提供的 PaginationState
实例的一些其他 UI 逻辑结合使用。
子元素
PropertyColumn<TGridItem,TProp>
:可以在QuickGrid
组件中作为子元素,用于设置每一列的展示内容。
Title
:列的标题文本Property
:定义要在此列单元格中显示的值Sortable
:指示数据是否应按此列进行排序SortBy
:指定列的排序规则Align
:如果指定,则控制此列的表标题和正文单元格的对齐方式Class
:可选的 CSS 类名, 如果指定,则此列的表标题和正文单元格的类属性中会包含此属性Format
:指定值的格式字符串,需要TProp
类型实现IFormattable
PlaceholderTemplate
:如果指定,虚拟化网格将使用此模板来渲染尚未加载数据的单元格IsDefaultSortColumn
:是否启用默认排序对此列进行排序(根据InitialSortDirection
的设置)InitialSortDirection
:指示初始排序要按哪个方向排序(当IsDefaultSortColumn
为true
时起效)Grid
:获取QuickGrid<TGridItem>
组件的引用ColumnOptions
:如果指定,则指示此列具有此关联选项 UI, 默认情况下,用于显示此 UI 的按钮将包含在标题单元格中- 如果使用
HeaderTemplate
,则由该模板来渲染任何相关的“显示选项”UI 并调用网格
- 如果使用
HeaderTemplate
:设置此列的标题单元格模板HeaderContent
:用于设置此列标题单元的内容,与HeaderTemplate
的区别在于HeaderTemplate
属性适用于需要动态生成、复杂布局的列表头内容,而HeaderContent
属性适用于简单的静态表头内容。
TemplateColumn<TGridItem>
:可以在QuickGrid
组件中作为子元素,用于设置每一列内容单元的模板
- 属性跟
PropertyColumn
差不多,下面只记录PropertyColumn
中没有的属性 ChildContent
:指定此列每一行中要渲染的内容
示例
-
示例-1
@page "/promotion-grid" @using Microsoft.AspNetCore.Components.QuickGrid @rendermode InteractiveServer <PageTitle>Promotion Grid</PageTitle> <h1>Promotion Grid Example</h1> <QuickGrid Items="@people" > <PropertyColumn Property="@(p => p.PersonId)" Sortable="true" Title="ID"> </PropertyColumn> <PropertyColumn Property="@(p => p.Name)" Sortable="true" /> <PropertyColumn Property="@(p => p.PromotionDate)" Format="yyyy-MM-dd" Sortable="true" /> </QuickGrid> @code { private record Person(int PersonId, string Name, DateOnly PromotionDate); private IQueryable<Person> people = new[] { new Person(10895, "Jean Martin", new DateOnly(1985, 3, 16)), new Person(10944, "António Langa", new DateOnly(1991, 12, 1)), new Person(11203, "Julie Smith", new DateOnly(1958, 10, 10)), new Person(11205, "Nur Sari", new DateOnly(1922, 4, 27)), new Person(11898, "Jose Hernandez", new DateOnly(2011, 5, 3)), new Person(12130, "Kenji Sato", new DateOnly(2004, 1, 9)), }.AsQueryable(); }
-
示例-2
@inject DataSource Data <div class="grid"> <QuickGrid Items="@FilteredItems" Pagination="@pagination"> <TemplateColumn Title="Rank" SortBy="@rankSort" Align="Align.Center" InitialSortDirection="SortDirection.Ascending" IsDefaultSortColumn="true"> <img class="flag" src="flags/@(context.Code).svg" /> </TemplateColumn> <PropertyColumn Property="@(c => c.Name)" Sortable="true" Class="country-name"> <ColumnOptions> <div class="search-box"> <input type="search" autofocus @bind="nameFilter" @bind:event="oninput" placeholder="Country name..." /> </div> </ColumnOptions> </PropertyColumn> <PropertyColumn Property="@(c => c.Medals.Gold)" Sortable="true" Align="Align.Right" /> <PropertyColumn Property="@(c => c.Medals.Silver)" Sortable="true" Align="Align.Right" /> <PropertyColumn Property="@(c => c.Medals.Bronze)" Sortable="true" Align="Align.Right" /> <PropertyColumn Property="@(c => c.Medals.Total)" Sortable="true" Align="Align.Right" /> </QuickGrid> </div> <Paginator State="@pagination" /> @code { IQueryable<Country>? items; PaginationState pagination = new PaginationState { ItemsPerPage = 15 }; string nameFilter = string.Empty; GridSort<Country> rankSort = GridSort<Country> .ByDescending(x => x.Medals.Gold) .ThenDescending(x => x.Medals.Silver) .ThenDescending(x => x.Medals.Bronze); IQueryable<Country>? FilteredItems => items?.Where(x => x.Name.Contains(nameFilter, StringComparison.CurrentCultureIgnoreCase)); protected override async Task OnInitializedAsync() { items = (await Data.GetCountriesAsync()).AsQueryable(); } }