0

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

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

4

1 回答 1

6

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

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

ChildComponent.razor

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

    @code {
      [Parameter]
      public string Title { get; set; } 
     }

父组件.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();

        };
    }

希望这有效...

于 2019-09-20T19:43:42.430 回答