Blazor 是否支持直接将组件作为通用参数传递?

问题描述 投票:0回答:1

我遗漏了某些内容或本文档不足:https://learn.microsoft.com/en-us/aspnet/core/blazor/components/generic-type-support?view=aspnetcore-8.0所有示例都是关于传递数据,而我对(直接)传递组件感兴趣。

假设我有

MyComponent
和通用容器
MyContainer<TComponent>
。在容器 .razor 页面中我想写:

  @typeparam TComponent where TComponent : ComponentBase
  ...
  <h1>This is my component</h1>
  <TComponent></TComponent>

使用这样的代码,我收到错误“找到具有意外名称 TComponent 的标记元素”。

备注:直接表示不使用

DynamicComponent

c# blazor
1个回答
0
投票

既然你想直接传递一个组件并渲染它,我建议你向你的组件添加一个RenderFragment参数。

FooComponent.razor:

<h1>This is my component</h1>
@ChildContent

@code {
    [Parameter, EditorRequired]
    public required RenderFragment ChildContent { get; set; }
}

您可以传递一个组件来渲染该组件,如下所示:

<FooComponent>
    <MyCustomComponent />
</FooComponent>
© www.soinside.com 2019 - 2024. All rights reserved.