如何在 Blazor 中手动渲染组件?

问题描述 投票:0回答:0

我正在尝试在

Blazor Web Assembly
中手动渲染一组组件,但是我在使用
Attributes
ChildContent
时遇到了麻烦。

以下是我如何手动渲染一个组件:

private RenderFragment CreateComponent(List<cMenuItem> menuItems) => builder =>
        {
            try
            {
                builder.OpenComponent(0, typeof(CoreEmpty));
                builder.AddAttribute(1, "ChildContent", (RenderFragment)((builder2) => {
                    for (var i = 0; i < menuItems.Count; i++)
                    {
                        builder2.OpenComponent(Increment++, typeof(CoreMenuItem));
                        builder2.AddAttribute(Increment++, "Text", menuItems[i].mText);
                        if (menuItems[i].mItems.Count > 0) CreateComponent(menuItems[i].mItems);
                        builder2.CloseComponent();
                    }
                }));
                builder.CloseComponent();
                builder.CloseElement();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        };

但是我在初始化主要组件的时候渲染了它:

protected override void OnInitialized()
        {
            base.OnInitialized();

            // Set the only menu if there is only one
            if (Data != null )
                if(Data.Count == 1)
                {
                    Menu1 = Data[0];
                    CustomRender = CreateComponent(Menu1.mMenu);
                }
        }

这是我的

Razor
页面:

@inherits cCoreMenu

@if(Data.Count > 1)
{
    @foreach(cMenu menu in Data)
    {
        
    }

}else if(Data.Count  == 1)
{
    <RadzenMenu Click="@Menu1.OnClickMenu">
        @CustomRender
    </RadzenMenu>
}

CoreEmpty
只是一个虚拟组件,因为我需要一个组件来生成 ChildContent 属性。

它给了我以下错误:

blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Stack empty.
System.InvalidOperationException: Stack empty.
   at System.Collections.Generic.Stack`1[[System.Int32, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].ThrowForEmptyStack()
   at System.Collections.Generic.Stack`1[[System.Int32, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Pop()
   at Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.CloseRegion()
   at Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.AddContent(Int32 sequence, RenderFragment fragment)
   at Microsoft.AspNetCore.Components.CascadingValue`1[[Radzen.Blazor.RadzenMenu, Radzen.Blazor, Version=4.7.4.0, Culture=neutral, PublicKeyToken=null]].Render(RenderTreeBuilder builder)
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)

这是什么

Stack empty
错误?我该如何解决?

c# components blazor blazor-webassembly radzen
© www.soinside.com 2019 - 2024. All rights reserved.