【问题标题】:RazorComponent in Blazor included several times in the same page shares codeBlazor 中的 RazorComponent 多次包含在同一页面共享代码中
【发布时间】:2020-10-28 18:30:08
【问题描述】:

我有一个名为“MyComponent”的 RazorComponent,我已将它包含在下面代码中描述的另一个 RazorComponent 中。

@foreach (var MyComponentConfig in MyComponentsConfig.GetChildren())
{
    <MyComponent Session="@GetSessionService(MyComponentConfig.Key)"></MyComponent>
}

我认为这会在循环的每次迭代中创建一个单独的 MyComponent 实例,但似乎代码以某种方式共享。 “OnInitialize”函数在 MyComponent 中只调用一次,即使我在循环中有 5 次迭代。我怎样才能做到这一点,以便创建一个单独的 MyComponent 实例而不是共享实例?

【问题讨论】:

    标签: .net asp.net-core blazor blazor-server-side


    【解决方案1】:

    我认为这会在循环的每次迭代中创建一个单独的 MyComponent 实例,但似乎代码以某种方式共享。 “OnInitialize”函数在 MyComponent 中只调用一次,即使我在循环中有 5 次迭代。

    你错了。试试这个代码:

    MyComponent.cs

    <h3>MyComponent</h3>
    
    @code {        
        protected override void OnInitialized()
        {
            Console.WriteLine("OnInitialized: {0}", ID.ToString());
        }
    
        [Parameter]
        public int ID { get; set; }
    
    }
    

    家长

    @page "/"
    
    @for( var count = 1; count < 5; count++)
    {
        <MyComponent ID="@count"/>
    }
    
    @code
    {
        protected override void OnInitialized()
        {
            Console.WriteLine("Parent component initialized");
        }
    }
    

    结果:

    父组件初始化

    OnInitialized: 1

    OnInitialized: 2

    OnInitialized: 3

    OnInitialized: 4

    注意:最好将@key 指令属性附加到 MyComponent 组件,如下所示

    <MyComponent @key="MyComponentConfig" Session="@GetSessionService(MyComponentConfig.Key)"></MyComponent>
    

    您可以为@key 指令分配任何您想要的值,只要它是唯一的。在我的代码示例中,您可以这样做:

    <MyComponent  @key="@count" ID="@count"/>
    

    阅读更多here

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-15
      • 2019-07-09
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      相关资源
      最近更新 更多