中文网站制作,建网站怎样才能通过备案,wordpress 文章摘要,模板网站哪家好原文链接#xff1a;https://blazor-university.com/templating-components-with-renderfragements/使用 RenderFragments 模板化组件源代码[1]到目前为止#xff0c;我们已经创建了基于参数生成 100% 渲染输出的组件#xff0c;但组件并不总是那么简单。有时我们需要创建将… 原文链接https://blazor-university.com/templating-components-with-renderfragements/使用 RenderFragments 模板化组件源代码[1]到目前为止我们已经创建了基于参数生成 100% 渲染输出的组件但组件并不总是那么简单。有时我们需要创建将组件使用者提供的标记与他们自己的渲染输出混合的组件。将内容作为 HTML 编码的字符串参数传递给组件会非常混乱更不用说难以管理Collapsible contentLots of encoded HTML for your entire view here/而且除了维护的噩梦之外嵌入的 HTML 也只能是基本的 HTML 标记没有 Blazor 组件。基本上它是没有用的而且显然不应该这样做。正确的方法是使用 RenderFragment。子内容如果我们创建一个名为 Collapsible 的新组件一个完全空的 .razor 文件如您所见我们可以在 Index.razor 页面中使用它如下所示Collapsible/但是如果我们想嵌入一些内容呢试一试然后查看浏览器控制台输出中的错误。CollapsibleHello world!/CollapsibleWASMSystem.InvalidOperationException“TemplatedComponents.Components.Collapsible”类型的对象没有与名称“ChildContent”匹配的属性。RenderFragment 类现在更改 Collapsible 组件使其具有名为 ChildContent 的属性一种 RenderFragment 类型并确保使用 [Parameter] 属性对其进行修饰。code {[Parameter]public RenderFragment ChildContent { get; set; }
}这些是 Blazor 用于将嵌入内容注入组件的标准。嵌入的内容可能是您想要的任何内容纯文本、HTML 元素、更多 razor 标记包括更多组件以及嵌入内容的内容可以通过添加 ChildContent 输出到组件标记中的任何位置。div classrowa href# onclickToggle classcol-12ActionText/aif (!Collapsed){div classcol-12 card card-bodyChildContent/div}
/divcode
{[Parameter]public RenderFragment ChildContent { get; set; }[Parameter]public bool Collapsed { get; set; }string ActionText { get Collapsed ? Expand : Collapse; }void Toggle(){Collapsed !Collapsed;}
}多个渲染片段当我们在组件内编写标记时Blazor 将假定它应该分配给组件上的一个参数该参数是从 RenderFragment 类派生的并命名为 ChildContent。如果我们希望使用不同的名称或多个渲染片段那么我们必须在标记中明确指定参数的名称。MyComponentHeaderh1The header/h1/HeaderFooterThis is the footer/FooterChildContentThe ChildContent render fragment must now be explicitly named because we havemore than one render fragment parameter in MyComponent.It doesnt have to be named ChildContent./ChildContent
/MyComponent在前面的示例中我们只需要显式指定 ChildContent因为我们显式使用了一个或多个其他渲染片段页眉和页脚。如果我们不想指定 Header 和 Footer 则无需显式命名 ChildContentBlazor 将假定 MyComponent 和 /MyComponent 之间的所有标记都是为 ChildContent 渲染片段。有关详细信息请参阅将数据传递给 RenderFragment[2]。参考资料[1]源代码: https://github.com/mrpmorris/blazor-university/tree/master/src/TemplatedComponents/TemplatedComponents