Blazor 》 Component。
ASP.NET Core Razor components
went over again.
Use @key to control the preservation of elements and components
可以使用@key
来增加渲染的HTML元素到组件之间的对应关系。
用作@key
的标的要稳定,一旦其发生变化,组件要重新渲染。
使用
@key
元素只在同一元素下才能互相比对
如何挑选@key
的值:
- 模型标的现例
- 唯一的标识符
若key之间存在冲突,Blazor会抛出异常
Apply an attribute
可以在组件上通过@attribute
添加属性,以[Authorize]
为例:
@page "/"
@attribute [Authorize]
Conditional HTML element attributes
HTML element attribute properties are conditionally set based on the .NET value. If the value is false or null, the property isn’t set. If the value is true, the property is set
更多参考https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-6.0
Raw HTML
MarkupString类型的值会被当作HTML或者SVG片段解析后插入DOM,示例:
@page "/markup-string-example"
@((MarkupString)myMarkup)
@code {
private string myMarkup =
"<p class=\"text-danger\">This is a dangerous <em>markup string</em>.</p>";
}
Razor templates
Razor模板形如:
@<{HTML tag}>...</{HTML tag}>
使用示例:
@page "/razor-template"
@timeTemplate
@petTemplate(new Pet { Name = "Nutty Rex" })
@code {
private RenderFragment timeTemplate = @<p>The time is @DateTime.Now.</p>;
private RenderFragment<Pet> petTemplate = (pet) => @<p>Pet: @pet.Name</p>;
private class Pet
{
public string Name { get; set; }
}
}
Static assets
Blazor的物料存放在wwwroot目录下。可以使用/
引用。对于{project root}/wwwroot/images
下的logo.png,引用路径如下:
<img alt="Company logo" src="/images/logo.png" />
组件不支持tilde-slash(即
~/
)
Tag Helpers aren’t supported in components
Blazor不支持MVC中的Tag Helper。
Scalable Vector Graphics (SVG) images
略。
Whitespace rendering behavior
若非@preservewhitespace
的值为真,额外的空白会被削除:
- 元素前后的空白
- childcontent的前后空白
- C#代码块,比如
@if
或者@foreach
前后的空白
若要取消对空白的削除,可以在组件或者_Imports.razor中设置@preservewhitespace true
。
Generic type parameter support
使用@typeparam
为组件设置一个泛型参数,支持C#的where类型约束:
@typeparam TEntity where TEntity : IEntity
(本篇完)