【问题标题】:Blazor Wasm - How to update base components from an inherited component?Blazor Wasm - 如何从继承的组件更新基础组件?
【发布时间】:2022-11-16 00:05:46
【问题描述】:

我有一个包含两个组件的 Blazor Wasm 应用程序:

BaseComp.razor:

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

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

子组件.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 属性?

【问题讨论】:

    标签: .net asp.net-core blazor blazor-webassembly


    【解决方案1】:

    有了这段代码

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

    你继承自与 BaseComp 组合。您没有使用继承部分。

    因此,仅使用组合并按照@MarvinKlein 的答案进行操作,但删除@inherits 行。

    或者将代码更改为:

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

    【讨论】:

      【解决方案2】:

      您需要将其声明为参数并将值传递下去。

      BaseComp.razor:

      <h1>I'm base - @Text</h1>
      
      @code{
         [Parameter] public string Text {get; set;} = "Default";
      }
      

      ChildComponent.razor

      @inherits BaseComp
      
      <BaseComp Text="Text"/>
      
      <h1>Hello, only child text!</h1>
      
      @code {
          protected override void OnInitialized()
          {
              Text = "new";
          }
      }
      

      【讨论】:

      • 当我在 childComponent 上定义一个将传递给 baseComponent 的属性时,这很有效,但是还有其他方法可以实现吗?对于多个参数,这可能会变得非常冗长,因为我需要在 base 和 child 上定义相同的属性
      • 不幸的是没有。执行此操作的常用方法是创建一个自定义类,该类包含您的属性并将此实例向下传递。
      猜你喜欢
      • 2021-05-09
      • 2020-05-16
      • 2016-11-13
      • 2020-09-15
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      相关资源
      最近更新 更多