我有一个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
属性?
3条答案
按热度按时间kgsdhlau1#
我 想 使用 基本 组件 在 所有 页面 上 呈现 相同 的 网格 , 但 需要 一些 附加 逻辑 。
目前 的
ComponentBase
并未 针对 这 类 模板 设计 。您 可以 :
1.使用 设计 用于 执行 此 操作 的 不同 基础 组件 。
1.让 它 与
ComponentBase
一起 工作 。这 是 如何 使 它 与 ComponentBase 一起 工作 , 因为 描述 如何 构建 不同 的 组件 超出 了 SO 答案 的 范围 。
我们 的 Package 器 组件 :
中 的 每 一 个
和 代码 隐藏 文件 使 其 抽象 化 。
格式
我们 的 新
Index
。 这里 的 关键 是 我们 的 内容 不再 放在 顶部 块 中 - Razor 编译 器 将 其 编译 为BuildRenderTree
的 部分 。 相反 , 我们 在 单独 的RenderFragment
中 定义 它 。我们 的 顶部 块 现在 包含
RenderFragment
属性this.Body
, 我们 已经 将 包含 来自 模板 的 编译 代码 的 基类 的BuildRenderTree
方法 分配 给 该 属性 。格式
它 看 起来 是 这样 的 :
siv3szwd2#
有了这段代码
您从***继承,***使用BaseComp合成。您没有使用继承部分。
因此,只使用composition,并按照@MarvinKlein的答案,但删除
@inherits
行。或者将代码更改为:wi3ka0sx3#
您需要将其声明为参数并向下传递该值。
BaseComp.razor:
ChildComponent.razor