【问题标题】:How to pass a variable number of components to a blazor component如何将可变数量的组件传递给 Blazor 组件
【发布时间】:2021-10-27 05:01:37
【问题描述】:

我正在尝试为我的 Blazor webapp 构建一个基本对话框组件,它应该在表示对话框步骤的不同子组件之间进行转换。

但到目前为止,我还没有找到将可变数量的不同组件传递给此基本对话框的方法。

我希望用法看起来像这样:

<Dialog>
    <DialogItem>
        @*SomeComponent*@
    </DialogItem>
    <DialogItem>
        @*AnotherComponent*@
    </DialogItem>
</Dialog>

有一些组件库(如 Mudblazor)具有这样工作的组件,所以应该是可能的吧?

到目前为止我唯一能找到的是这样的:

@typeparam inputType

@foreach(var item in Items)
{
   @Template(TItem)
}

@code{
    [Parameter]
    public RenderFragment<inputType> Template { get; set; }
    [Parameter]
    public List<inputType> Items { get; set; }
}

但这不允许我以不同的方式呈现列表中的项目,还是我在这里遗漏了什么?

【问题讨论】:

    标签: c# blazor


    【解决方案1】:

    这里最好的方法是让父组件(这里是&lt;Dialog&gt;)成为子组件可以检测到的级联组件,然后在渲染时调用以将它们自己添加到列表中。

    Steve Sanderson 在他的 Tab 组件中演示了这一点,这里有一个示例: https://gist.github.com/SteveSandersonMS/f10a552e1761ff759b1631d81a4428c3

    【讨论】:

    • 看来它可以满足我的需要,谢谢!
    【解决方案2】:

    如果将来有人偶然发现这个问题,这就是我最终的结果:

    对话框组件:

    <CascadingValue Value="this">
        @ChildContent
    </CascadingValue>
    
    @ActiveNode?.Value.ChildContent
    
    @code {
        [Parameter]
        public RenderFragment? ChildContent { get; set; }
    
        LinkedList<DialogItem> DialogItems { get; } = new();
    
        LinkedListNode<DialogItem>? ActiveNode { get; set; }
    
        public void Add(DialogItem item)
        {
            DialogItems.AddLast(item);
            if (ActiveNode is null)
            {
                ActiveNode = DialogItems.First;
                StateHasChanged();
            }
        }
        public void Next()
        {
            if (ActiveNode != DialogItems.Last)
                ActiveNode = ActiveNode?.Next;
        }
        public void Previous()
        {
            if (ActiveNode != DialogItems.First)
                ActiveNode = ActiveNode?.Previous;
        }
    }
    

    DialogItem 组件:

    @code {
        [Parameter]
        public RenderFragment? ChildContent { get; set; }
    
        [CascadingParameter]
        Dialog? ParentDialog { get; set; }
    
        protected override void OnInitialized()
        {
            ParentDialog?.Add(this);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-18
      • 2021-04-05
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 2021-11-16
      • 2019-09-15
      • 1970-01-01
      相关资源
      最近更新 更多