簡體   English   中英

將 @ref 添加到循環中的 Blazor 組件

[英]Add @ref to a Blazor component in a loop

如何將@ref添加到循環內的 Blazor 組件?

@for (int i = 0; i < 10; i++)
{
    <MyComponent @ref="???"/> // I want to add this component to the list
}

@code
{
    List<MyComponent> components = new List<MyComponent>();
}

@Kahbazi 我無法回復,所以我必須在這里問。 __value 來自哪里?

我的解決方案如下:

@for (int i = 0; i < 10; i++)
{ 
    <MyComponent @ref="ComponentRef" />
}

@code {
    List<MyComponent> ComponentRefs = new List<MyComponent>();
    MyComponent ComponentRef {
        set { ComponentRefs.Add(value); }
    }
}

Blazor 編譯器現在的工作方式是,您可以在@ref屬性上注入C#代碼。 您可以使用它來將組件添加到列表中。

@for (int i = 0; i < 10; i++)
{
    <MyComponent @ref="components.Add((MyComponent)__value);//" />
}

@code
{
    List<MyComponent> components = new List<MyComponent>();
}

暫無
暫無

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

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