繁体   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