我想在 Blazor 页面上获取 Blazor 组件的所有实例:
页:
<div class="mb-4 pt-3">
<SearchFilter Refinement="@refinementAuthor" FilterTitle="Auteur"></SearchFilter>
</div>
<div class="mb-4 pt-3">
<SearchFilter Refinement="@refinementSubject" FilterTitle="Onderwerp"></SearchFilter>
</div>
<div class="mb-4 pt-3">
<SearchFilter Refinement="@refinementLanguage" FilterTitle="Taal"></SearchFilter>
</div>
如何获取三个"搜索过滤器"的列表?
我相信目前 Blazor 中不存在这样的功能。但是,您可以通过向列表对象添加组件引用(@ref指令属性(来创建组件列表,如下所示:
ChildComponent.razor
<h3>@Title</h3>
@code {
[Parameter]
public string Title { get; set; }
}
用法
<ChildComponent @ref="ChildComponent1" Title="ChildComponent 1"/>
<ChildComponent @ref="ChildComponent2" Title="ChildComponent 2" />
<ChildComponent @ref="ChildComponent3" Title="ChildComponent 3" />
@if (components != null)
{
@foreach (var component in components)
{
<p>@component.Title</p>
}
}
@code{
ChildComponent ChildComponent1;
ChildComponent ChildComponent2;
ChildComponent ChildComponent3;
List<ChildComponent> components;
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
components = new List<ChildComponent>();
components.Add(ChildComponent1);
components.Add(ChildComponent2);
components.Add(ChildComponent3);
StateHasChanged();
}
}
}
请注意,只有在呈现页面组件后才会填充列表。您之前无法访问这些组件,因为它们尚未创建...