在我們從父組件傳參數給子組件時,可以通過子組件定義的[Parameter]特性的公開屬性進行傳值,但是當我們需要傳遞多個值的時候,就需要通過[Parameter]特性定義多個屬性,有沒有更簡便的方式?
我們可以使用定義 IDictionary<string,object>類型的參數,并使用[Parameter(CaptureUnmatchedValues =true)]特性進行標注,這樣在父組件中嵌套子組件時,可以任意的傳遞參數。
子組件:
<h3>ParameterChild</h3>
<ul>@if (Parameters != null){@foreach (var item in Parameters){<li>key=@item.Key,value=@item.Value</li>}}
</ul>
@code {[Parameter(CaptureUnmatchedValues = true)]public Dictionary<string, object>? Parameters { get; set; }
}
我們在子組件中將所有參數展示出來,用于驗證參數是否傳遞成功
父組件:
@page "/demoPage"
@rendermode InteractiveAuto
<h3>DemoPage</h3>
<ParameterChild class="123" x1 ="2"></ParameterChild>@code {}
運行結果:
我們通過運行結果可以看到,參數被正確的傳遞到了子組件
參數設置順序
@attributes 特性在應用字典中的任意參數時,是從右向左進行設置的。
下面我們還是用一段代碼示例看看是怎么處理的
子組件:
<h3>ParameterChild</h3>
<div @attributes=Parameters x1="200"></div>
<ul>@if (Parameters != null){@foreach (var item in Parameters){<li>key=@item.Key,value=@item.Value</li>}}
</ul>
@code {[Parameter(CaptureUnmatchedValues = true)]public Dictionary<string, object>? Parameters { get; set; }
}
父組件:
@page "/demoPage"
@rendermode InteractiveAuto
<h3>DemoPage</h3>
<ParameterChild class="123" x1 ="2"></ParameterChild>@code {}
我們在子組件和父組件中都為div賦值了x1屬性,<div @attributes=Parameters x1=“200”>,根據參數設置的順序,x1="200"在右側,優先進行了設置,我們來看看運行的結果是否和我們預期的一致
運行結果:
運行的結果和我們的預期是完全一致的,如果調整<div @attributes=Parameters x1=“200”>中x1和 @attributes的順序,結果應該是賦值x1=2
我們調換順序做一次嘗試
修改后的子組件如下:
<h3>ParameterChild</h3>
<div x1="200" @attributes=Parameters></div>
<ul>@if (Parameters != null){@foreach (var item in Parameters){<li>key=@item.Key,value=@item.Value</li>}}
</ul>
@code {[Parameter(CaptureUnmatchedValues = true)]public Dictionary<string, object>? Parameters { get; set; }
}
我們運行下看看結果
結果和我們預期一樣,發生了變化