我如何在另一个组件中即时多次动态渲染 blazor 组件(例如:每次单击按钮)

0 blazor blazor-server-side blazor-client-side

我想在每次单击按钮时通过动态添加其他 blazor 组件来更新视图。我怎样才能做到这一点。

例如:每次单击组件 1 上的按钮时,应立即将组件 2 添加到组件 1 中。

Isa*_*aac 6

注意:此示例是很久以前创建的...目前 Blazor 支持可用于相同目的的高级功能。

您可以为此使用模板化组件阅读链接部分,并尝试将我的示例转换为模板化组件。

子组件.razor

<li><div>@Title</div></li>  

    @code {
      [Parameter]
      public string Title { get; set; } 
     }
Run Code Online (Sandbox Code Playgroud)

父组件.razor

    <p>Type the title for the new component and then click the button<p>

    <input type="text" @bind="@Title" />

   <button @onclick="@AddComponent">New Component</button>

    <div>   
     @if (!list.Any())
        {
            <p>You have no items in your list</p>
        }
        else
        {
            <ul>
                @foreach (var item in list)
                {
                    @item();
                }
            </ul>
        }
    </div>

    @code {

        public List<RenderFragment> list { get; set; }
        public string Title { get; set; }

        protected override void OnInitialized()
        {
           list = new List<RenderFragment>();
        }


        protected void AddComponent()
        {
                list.Add(CreateDynamicComponent());

        }


        RenderFragment CreateDynamicComponent() => builder =>
        {

            builder.OpenComponent(0, typeof(ChildComponent));
            builder.AddAttribute(1, "Title", "Title:  " + Title);
            builder.CloseComponent();

        };
    }
Run Code Online (Sandbox Code Playgroud)

希望这有效...