.net Blazor Wasm -如何从继承的组件更新基础组件?

tag5nh1u  于 2022-11-19  发布在  .NET
关注(0)|答案(3)|浏览(212)

我有一个Blazor Wasm应用程序,它有两个组件:
BaseComp.razor:

<h1>I'm base - @Text</h1>

@code{
    protected string Text {get; set;} = "Default";
}

ChildComponent.razor

@inherits BaseComp

<BaseComp/>

<h1>Hello, only child text!</h1>

@code {
    protected override void OnInitialized()
    {
        Text = "new";
    }
}

页面上将显示以下内容:

I'm base - Default
Hello, only child text!

如何从childComponent更新baseComponent的Text属性?

kgsdhlau

kgsdhlau1#

我 想 使用 基本 组件 在 所有 页面 上 呈现 相同 的 网格 , 但 需要 一些 附加 逻辑 。
目前 的 ComponentBase 并未 针对 这 类 模板 设计 。
您 可以 :
1.使用 设计 用于 执行 此 操作 的 不同 基础 组件 。
1.让 它 与 ComponentBase 一起 工作 。
这 是 如何 使 它 与 ComponentBase 一起 工作 , 因为 描述 如何 构建 不同 的 组件 超出 了 SO 答案 的 范围 。
我们 的 Package 器 组件 :

<h3 class="text-primary m-2 p-2">Wrapper</h3>
<div class="bg-primary text-white m-2 p-2">
@this.Body
</div>

@code {
    protected abstract RenderFragment? Body { get; }
}

中 的 每 一 个
和 代码 隐藏 文件 使 其 抽象 化 。

public abstract partial class Wrapper { }

格式
我们 的 新 Index 。 这里 的 关键 是 我们 的 内容 不再 放在 顶部 块 中 - Razor 编译 器 将 其 编译 为 BuildRenderTree 的 部分 。 相反 , 我们 在 单独 的 RenderFragment 中 定义 它 。
我们 的 顶部 块 现在 包含 RenderFragment 属性 this.Body , 我们 已经 将 包含 来自 模板 的 编译 代码 的 基类 的 BuildRenderTree 方法 分配 给 该 属性 。

@page "/"
@inherits Wrapper

@this.Content

@code {
    // Where we put the base Template class Render Fragment
    private RenderFragment Content;

    // Ctor - must call base and then we load the base Template class content
    public Index() : base()
        => this.Content = (builder) => base.BuildRenderTree(builder);

    // Our content that the Razor compiler will build in Body
    // __builder is the built in Razor compiler RenderTreeBuilder 
    protected override RenderFragment Body => (__builder) =>
    {
        <PageTitle>Index</PageTitle>

        <h1>Hello, world!</h1>

        <div>Welcome to your new app.</div>

        <SurveyPrompt Title = "How is Blazor working for you?" />
    };
}

格式
它 看 起来 是 这样 的 :

siv3szwd

siv3szwd2#

有了这段代码

@inherits BaseComp
<BaseComp/>  @* a new instance, not inheritance *@

您从***继承,***使用BaseComp合成。您没有使用继承部分。
因此,只使用composition,并按照@MarvinKlein的答案,但删除@inherits行。或者将代码更改为:

@inherits BaseComp

@*<BaseComp />*@
@{ base.BuildRenderTree(__builder); }

<h1>Hello, only child text!</h1>
wi3ka0sx

wi3ka0sx3#

您需要将其声明为参数并向下传递该值。
BaseComp.razor:

<h1>I'm base - @Text</h1>

@code{
   [Parameter] public string Text {get; set;} = "Default";
}

ChildComponent.razor

<BaseComp Text="Text"/>

<h1>Hello, only child text!</h1>

@code {
    protected override void OnInitialized()
    {
        Text = "new";
    }
}

相关问题