Blazor University (9)组件 — 代码生成 HTML 属性
原文鏈接:https://blazor-university.com/components/code-generated-html-attributes/
代碼生成 HTML 屬性
Razor 在條件 HTML 輸出或在 for 循環中輸出 HTML 時非常棒,但在元素本身內的條件代碼方面,事情就有點棘手了。例如,以下代碼無法編譯,因為您無法在元素的 < 和 > 內添加 C# 控制塊。
<img@foreach(var?nameAndValue?in?AdditionalAttributes){@nameAndValue.Key?=?@nameAndValue.Value}?src="https://randomuser.me/api/portraits/lego/1.jpg"?/>@code {Dictionary<string,?object>?AdditionalAttributes;protected?override?void?OnInitialized(){AdditionalAttributes?=?new?Dictionary<string,?object>{["id"]?=?"EmmetImage",["alt"]?=?"A?photo?of?Emmet"};base.OnInitialized();} }我們可能嘗試的下一個方法是編寫一個返回字符串的方法,并在 < 和 > 字符內調用它。
<div?@IfYouCanSeeThisTextThenTheCodeWasNotExecutedHere?/> <span>@IfYouCanSeeThisTextThenTheCodeWasNotExecutedHere</span>@code {string?IfYouCanSeeThisTextThenTheCodeWasNotExecutedHere?=?"The?code?here?was?executed"; }但這也不起作用。前面的示例將輸出以下 HTML。
<div?@ifyoucanseethistextthenthecodewasnotexecutedhere=""></div> <span>The?code?here?was?executed</span>`Razor 只會在以下位置執行 C# 代碼:
在元素的內容區域內,例如 <span>@GetSomeHtml()</span>。
在確定要分配給元素屬性的值時,例如 <img src=@GetTheImageForTheUrl() />。
在 @code 部分中。
我們需要用來為 HTML 元素生成一個或多個屬性 + 值的技術稱為“屬性展開”。屬性展開涉及將 Dictionary<string, object> 分配給具有特殊名稱 @attribute 的屬性。
<div?@attributes=MyCodeGeneratedAttributes/>@code {Dictionary<string,?object>?MyCodeGeneratedAttributes;protected?override?void?OnInitialized(){MyCodeGeneratedAttributes?=?new?Dictionary<string,?object>();for(int?index?=?1;?index?<=?5;?index++){MyCodeGeneratedAttributes["attribute_"?+?index]?=?index;}} }前面的代碼將輸出一個具有 5 個屬性的 <div>。
<div?attribute_1="1"?attribute_2="2"?attribute_3="3"?attribute_4="4"?attribute_5="5"></div>特殊情況
一些 HTML 屬性,例如 readonly 和 disabled 不需要任何值——它們僅存在于元素上就足以使它們生效。事實上,即使應用諸如 false 之類的值仍然會激活它們。以下 <input> 元素將是只讀和禁用的。
<input?readonly="false"?disbabled="false"/>在 razor 視圖中,規則略有不同。如果我們輸出 readonly=@IsReadOnly 或 disabled=@IsDisabled - 只要分配的值為 false,razor 根本不會輸出該屬性;當分配的值為 true 時,razor 將在不分配值的情況下輸出元素。
<input readonly=@true disabled=@false/> 將導致生成的 HTML 完全不包含 disabled 屬性。
總結
以上是生活随笔為你收集整理的Blazor University (9)组件 — 代码生成 HTML 属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Azure DevOps 中 Dapr项
- 下一篇: C# 发出异步的Get请求