如何将 html/组件传递给 blazor 模板?

Ven*_*sky 0 c# blazor asp.net-blazor

这是我的案例:

我有一个组件Foo,我希望它有一个名为 blazor 的模板Wrapper,该模板将用于包装 的某些Foo内容。

我需要做的是类似的事情

正常使用:

<Foo>
    <Wrapper>
        <div>
            <p>Something in the wraper</p>
            @context // context should be some content of Foo
        </div>
    </Wraper>
</Foo>
Run Code Online (Sandbox Code Playgroud)

里面Foo

@* Other content of Foo*@

@if(Wrapper != null){
    @* Pass to Wrapper some content of Foo *@
    Wrapper(@* How to render html/components here? *@)
}

@* Other content of Foo*@
Run Code Online (Sandbox Code Playgroud)

但是没有办法为模板传递html或组件吗?

我怎样才能做到这一点?

Mis*_*goo 5

在这种情况下,您的 Wrapper 是一个 RenderFragment,您想要接受另一个 RenderFragment,因此它的签名是

[Parameter] public RenderFragment<RenderFragment> Wrapper {get;set;}
Run Code Online (Sandbox Code Playgroud)

这是完整的 Foo.razor

@* Other content of Foo*@
<h1>This is Foo</h1>

@if(Wrapper != null){
    @* Pass to Wrapper some content of Foo *@
    @Wrapper(
        @<h2>This comes from Foo</h2>
    )
}

<h1>There is no more Foo</h1>

@code 
{
    [Parameter] public RenderFragment<RenderFragment> Wrapper {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

仔细注意 Wrapper 调用中的构造。

  1. 从 @Wrapper 开始,所以这是来自 Razor 的调用

  2. Wrapper 之后的open(让你回到 C# 领域,所以 -

  3. 用于@交换回 Razor 代码。

  4. 现在您可以使用 Razor/HTML 标记<h2>This comes from Foo</h2>

  5. Wrapper使用 a关闭呼叫)

这就是如何使用将 RenderFragment 作为上下文的 RenderFragment。

其输出将是

这是福

包装纸里有东西

这来自于 Foo

没有了 Foo

您可以在这里测试一下https://blazorfiddle.com/s/ox4tl146