dynamic - 如何在 Blazor 中引用通过 DynamicComponent 创建的组件?
问题描述
我正在使用 DinamicComponent 渲染组件,我需要调用在子组件中找到的函数。我找不到对 DinamicComponents 使用 @ref 的等价物,以便我可以引用来调用该函数。
这是父组件
<div class="tab-content">
@foreach (VerticalTabComponent.TabModel oneTabItem in VerticalTabsList)
{
<div class="tab-pane fade show @(oneTabItem.TabIndex == SelectedTabIndex ? "active" : "")" @key=@($"VTabDivDynamic_{TabPrefix}_{oneTabItem.TabIndex.ToString()}")>
<DynamicComponent
Type=@System.Type.GetType(oneTabItem.TabComponent)
Parameters=@oneTabItem.TabParameters>
</DynamicComponent>
</div>
}
</div>
这是 Blazor 组件选项卡中的代码
public partial class TabComponent
{
[Parameter]
public EventCallback<string> InsertUpdateCallback { get; set; }
protected override async Task OnInitializedAsync()
{
await CallAnyfunctionAsync();
}
private async Task<bool> LoadDataGrid()
{
//this is the function I need to call from parent
}
}
如何从父组件调用 Load Grid 函数?
解决方案
通常在 Blazor 中,我们用于@Ref
获取对组件的引用,但正如您所见,这不适用于DynamicComponent
.
一种解决方法是向[Parameter]
组件添加一个名为类似的东西Register
,这是一个将泛型类型设置为组件类型的操作。然后,您可以添加代码来处理OnParametersSet
以在组件中调用此方法。
然后,您可以在您的参数中添加一个Register
参数,TabParameters
该参数会通过引用进行更新。
下面的示例代码将添加到SurveyPrompt
组件中:
/// <summary>
/// will be called when params set
/// </summary>
[Parameter] public Action<SurveyPrompt> Register { get; set; }
protected override void OnParametersSet()
{
if (Register != null)
{
// register this component
Register(this);
}
}
您添加一个Register
带有Action<type>
值的参数。这是一个例子:
SurveyPrompt sp1 = null;
void Register1(SurveyPrompt survey)
{
sp1 = survey;
Console.WriteLine("SP1 has title " + sp1.Title);
}
protected override void OnInitialized()
{
Action<SurveyPrompt> p1 = Register1;
params1 = new Dictionary<string, object>()
{
{ "Title", "Survey Title Here" },
{ "Register", p1 }
};
}
IDictionary<string, object> params1;
推荐阅读
- python - 为什么 Series 的 group 和 aggregate 比单列 DataFrame 更快?
- vb.net - Interop Word Add Shape Giving Exeption - 未找到类型“ApplicationClass”的公共成员“Shapes”
- algorithm - 哪种算法有助于在具有所有负边(成本)的图中找到从源到汇的最短路径?
- java - Power mockito 验证静态调用真实方法
- visual-studio-2017 - Visual Studio 2017 如何跳转到 C++ 基础方法
- bitbucket - 来自其他作者的 Bitbucket 提交未拉动
- docker - 如何将 Docker 的 `--privileged` 标志添加到 Kubernetes pod 规范容器 YAML 定义
- excel - 从excel单元格中获取几个标签
- javascript - 在AngularJS中设置范围之前如何等待图像加载?
- canvas - 是否可以在 Cesium 上放置 HTML 元素(项目)?