簡體   English   中英

如何在 Blazor 中呈現定義為對象的組件?

[英]How can I render a component in Blazor that is defined as object?

我有以下代碼:

<div>
@if (Components != null && Components.Count != 0) {
   foreach (ComponentBase child in Components) {
      // Render the child component here
   }
}
</div>

如何使用 RenderFragment 來渲染子對象? 子對象是一個模板組件,它繼承了其他類(上面有 ComponentBase)。

問題是子對象已經設置了所有參數,所以我不想使用對象數據再次設置所有 RenderFragment 參數。

我在 foreach 循環中嘗試過但沒有奏效的事情:

foreach (ComponentBase child in Components) {
  @child // <-- does render the class text
}

foreach (ComponentBase child in Components) {
  <ComponentBase>@child</ComponentBase> // <-- error
}

foreach (ComponentBase child in Components) {
  RenderFragment renderChild = (builder) => { builder.OpenComponent(0, child.GetType()); builder.CloseComponent(); };
@renderChild; // <-- I want to render the child object as this does nothing
}

這幾乎是 .net6 中即將推出的 DynamicComponent 的等效項

您可以通過Type傳遞Type或通過TypeString傳遞Type TypeString

public class ComponentView : ComponentBase
{
    [Parameter]
    public Type Type { get; set; }

    [Parameter]
    public string TypeString { get; set; }

    private Dictionary<string, object> parameters;

    [Parameter]
    public Dictionary<string, string> Values { get; set; }

    protected override void OnParametersSet()
    {
        if (Values is null) {
            parameters = null;
        }
        else {
            parameters = new Dictionary<string, object>();
            foreach (var pair in Values) {
                parameters[pair.Key] = pair.Value;
            }
        }
        base.OnParametersSet();
    }



    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        if (Type is null) {
            if (string.IsNullOrWhiteSpace(TypeString)) {
                throw new Exception("You must use either Type or the TypeString paramater");
            }
            Type = Type.GetType(TypeString);
        }

        if (Type is not null) {
            builder.OpenComponent(1, Type);

            if (parameters is not null) {
                builder.AddMultipleAttributes(2, parameters);
            }
            builder.CloseComponent();
        }
        base.BuildRenderTree(builder);
    }
}

從這個回購

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM