1.简单介绍
.NET 8 引进了一个新的特性 ,一对可以控制子组件显示内容的组件 SectionOutlet和SectionContent。两个组件可以通过SectionName或者SectionId进行关联。类似于MVC中的RenderSection的作用。SectionContent中的内容是以RenderFragment提供给SectionOutlet的。
2.代码
2.1 SectionName方式
比如在MainLayout中, 加入了一个 <SectionOutlet SectionName="Subject"/>,这样使用这个布局页的组件可以把特定内容显示在SectionOutlet的位置。
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<div class="top-row px-4">
<SectionOutlet SectionName="Subject" />
</div>
<article class="content px-4">
@Body
</article>
</main>
</div>
在使用MainLayout的组件中,可以使用SectionContent如下
@page "/weather"
<PageTitle>Weather</PageTitle>
<SectionContent SectionName="Subject">
<strong>Blazor Section Check</strong>
</SectionContent>
运行一下,发现右上方确实出现了 Blazor Section Check的内容
2.2 SectionId 方式
上面使用的是SectionName,也可以使用SectionId的方式
在MainLayout页面中,把SectionOutlet的内容调整为如下,
同时在Weather组件页面中,把内容变成,
运行一下,发现页面右上方的内容也变化成设定的值了
3.总结
以上简单尝试了一下Blazor中的Section特性。一个组件的SectionContent也可以呈现在另外一个平级的组件的SectionOutlet中,假定SectionContent中有一个按钮,这个按钮虽然呈现在另外一个组件中,但是它仍然调用的是源组件的方法。
Blazor section和MVC中RenderSection功能类似,起到了占位的作用。
如果哪里有错误,麻烦告之,谢谢谢谢