基本组件布局继承blazor

基本组件布局继承blazor,blazor,Blazor,假设我的大多数组件都有一个标题。我想创建一个具有header变量的基本组件,并使所有其他组件从该组件继承并设置header。所以我有 基本组件 @inherits LayoutComponentBase; <h1>@header</h1> @Body @code { protected string header; } @inherits BaseComponent; "internal component text" @code { prote

假设我的大多数组件都有一个标题。我想创建一个具有header变量的基本组件,并使所有其他组件从该组件继承并设置header。所以我有

基本组件

@inherits LayoutComponentBase;

<h1>@header</h1>

@Body

@code {

    protected string header;
}
@inherits BaseComponent;

"internal component text"

@code {
  protected override void OnInitialized()
    {
         base.header = "Setting header for the parent"
    }
}
//No need to inherit, only inject...
// @inherits BaseComponent;

@inject GlobalUtilities gu

<p>Something here</p>

@code {
    protected void OnInitialized()
    {
        gu.SetMainTitle("Whatever you want");
    }
}
这将编译并显示,没有错误,但基本标头不会显示。这就像基础中的任何东西都不会被渲染一样。我做错了什么

附言


我还尝试了
@layout BaseComponent
,甚至同时尝试了这两个指令。

它永远不会以您显示的方式工作,因为从内部组件设置父组件的属性不会触发渲染。 AFAIK解决此问题的正确方法是拥有一个独立的服务类,该类包含一些公共状态(在您的情况下为当前页面标题),并通过事件操作的含义将其注入需要更改的每个组件:

可能是这样的:

public class GlobalUtilities
{
    public string MainPageTitle { get; private set; } = "Home (default value)";

    public event Action OnMainTitleChanged;

    public void SetMainTitle(string text)
    {
        MainPageTitle = text;
        OnMainTitleChanged.Invoke();
    }
}
在Startup.cs中的管道上注册它:

services.AddScoped<UtilsGlobales>();
services.addScope();
它应该注册为作用域,因为它的生存期与当前连接成对

然后在您需要的所有子体组件上使用它:

组件

@inherits LayoutComponentBase;

<h1>@header</h1>

@Body

@code {

    protected string header;
}
@inherits BaseComponent;

"internal component text"

@code {
  protected override void OnInitialized()
    {
         base.header = "Setting header for the parent"
    }
}
//No need to inherit, only inject...
// @inherits BaseComponent;

@inject GlobalUtilities gu

<p>Something here</p>

@code {
    protected void OnInitialized()
    {
        gu.SetMainTitle("Whatever you want");
    }
}
//无需继承,只需注入。。。
//@继承BaseComponent;
@注射球蛋白
这里有东西

@代码{ 受保护的无效初始化() { gu.SetMainTitle(“任何你想要的”); } }

希望有帮助

在撰写本文时,派生的razor组件自动实现其基类的所有方法,包括BuildRenderTree(它呈现您在razor文件中键入的HTML标记)。当您不键入任何内容时,该方法将不会尝试单独调用基本BuildRenderTree方法。因此,您需要手动执行此操作,如下所示:

@inherits BaseComponent;

@{
    base.BuildRenderTree(__builder);
}

@code {
  protected override void OnInitialized()
    {
         base.header = "Setting header for the parent"
    }
}

要解决这个问题,您需要学习Blazor组件模型和Blazor中的布局机制。没有快捷方式…父级的静态内容(我有一些测试词)也没有显示,但…好像父级组件不存在。堆栈溢出时不建议使用纯代码答案,因为它们没有解释如何解决问题。请编辑您的答案,解释此代码如何回答问题,以及如何改进现有问题,以便对OP以及其他有类似问题的用户有用。@FluffyKitten您完全正确,当时是凌晨2点,我的大脑被炸了。我添加了一些细节!