簡體   English   中英

Blazor:將組件傳遞給 RenderFragment

[英]Blazor : Pass Component to RenderFragment

我正在嘗試將 ListItem 組件傳遞給要顯示的 List 組件。

ListItem 組件如下所示:Razor:

 <li> @Item </li>

C#

using Microsoft.AspNetCore.Components;
namespace Components
{
    public partial class TextListItem
    {
        [Parameter]
        public new string Item { get; set; }
    }
}

這應該只顯示一個包含文本的列表項。

列表組件如下所示:Razor:

 @typeparam T <ul> @foreach(T item in Items) { @ChildContent(item) } </ul>

using Microsoft.AspNetCore.Components;
namespace Components
{
public partial class ListComponent<T> 
    {
        [Parameter]
        public List<T> Items { get; set; }

        [Parameter]
        public RenderFragment<T> ChildContent { get; set; }

    }
}

這應該只是用列表項填充無序列表。

然后在索引中我有類似的東西:

 <ListComponent Items = "@textList" > @context.Item </ListComponent> @code{ private List<TextListItem> textList; protected override void OnInitialized() { base.OnInitialized(); textList = new List<TextListItem>() { new TextListItem(){Item ="one" }, new TextListItem(){Item ="two" }, new TextListItem(){Item ="three" }, }; } }

我沒有從列表 textList 中取回 HTML,只取回 Item 中的文本。 我讓這個復雜,因為我想為不同類型的列表獲取 HTML 的各種片段。 為什么我不拿回 HTML? 我想我應該這樣做。 謝謝!

您真正想要做的是創建一個模板化組件,它使 TextListItem 的使用變得多余,也就是說,無論如何,這不僅不會在您的代碼中使用,而且是不可能的。

這:在 Blazor 中不允許使用new TextListItem(){Item ="one" } 你不能像那樣創建一個 Razor 組件...... Item 是一個組件參數,你不能這樣設置它。 您是否收到警告消息,告訴您不要在組件外部修改組件的 state。

這是如何做到這一點的代碼。 復制和測試。

ListComponent.razor.cs

public partial class ListComponent<TValue>
    {
        [Parameter]
        public List<TValue> Items { get; set; }

        [Parameter]
        public RenderFragment<TValue> ChildContent { get; set; }

    }

ListComponent.razor

@typeparam TValue
<ul>
    @foreach (TValue item in Items)
    {
        @ChildContent(item)
    }
</ul>

@code {

}

索引.razor

@page "/"

<ListComponent Items="@textList" Context="Item">
    <li>@Item</li>
    
</ListComponent>
@code{
   
    private List<string> textList = new List<string> { "one", "two", "three" };
   
}

我能夠通過使用DynamicComponent使您的示例工作: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent?view=aspnetcore-6.0

<ListComponent Items="@textList">
    <DynamicComponent Type="@context.GetType()" 
                      Parameters="@(new Dictionary<string, object> { { nameof(context.Item), context.Item } })" />
</ListComponent>

@code {
    private List<TextListItem> textList;

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

        textList = new List<TextListItem>()
        {
            new TextListItem() { Item = "one" },
            new TextListItem() { Item = "two" },
            new TextListItem() { Item = "three" },
        };
    }
}

我從未在我的項目中使用過它,這可能是一個糟糕的主意,所以請嘗試使用它並自擔風險。

暫無
暫無

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

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