简体   繁体   中英

How to use string.Format for @ref

I have many dropdown items in my real code. Shown a sample below. I am rewriting the code to reduce the number of lines, so that it is easier to read and maintain.

Please see the old working code in the first section and the new code I have tried (at the bottom);

Old code:

@if (Item.Contains("One"))
{
    <li class="dropdown-item">
        <button @ref="_btn1Ref" class="Scale" id="0" @onclick=OpenDialog1>Current</button>
    </li>
    <li class="dropdown-item">
        <button @ref="_btn2Ref" class="Scale" id="1" @onclick=OpenDialog2>UpHole Voltage</button>
    </li>
} 
                            
@if (Item.Contains("Two"))
{
    <li class="dropdown-item">
        <button @ref="_btn4Ref" class="Scale" id="3" @onclick=OpenDialog4>Head Tension</button>
    </li>
    <li class="dropdown-item">
        <button @ref="_btn5Ref" class="Scale" id="4" @onclick=OpenDialog5>Head Tension Temp</button>
    </li>
}

New cod - Added as per suggestion:

List<string> name = new List<string>
                {"nothing", "one", "two", "three", "four"};
List<string> btnReference = new List<string>
            {"nothing", "_btn1Ref", "_btn2Ref", "_btn3Ref", 
             "_btn4Ref"
            };
List<string> openDialog = new List<string>
             {"nothing", "OpenDialog1", "OpenDialog2", "OpenDialog3", 
              "OpenDialog4"
            };

@for (var i = 1; i < 5; i++)
{
    bool isAvailable = false;  

    if (!isAvailable && NavItem.Contains("PH1"))
        isAvailable = i >= 1 && i <= 2;

    if (!isAvailable && NavItem.Contains("PH2"))
        isAvailable = i >= 3 && i <= 4;

    if (isAvailable)
    {
     <li class="dropdown-item">
            <button ref="@btnReference[i]" class="Scale" id="@i-1" onclick=@openDialog[i]>@tools[i]</button>
     </li>
    }
}

Can anyone guide me how I rewrite the above line. Thank you.

You could store your references in a list and use them this way:

@inject IJSRuntime JSRuntime

@for(int i=0; i < btnReferences.Count; i++)
{
  var iCopy = i;
  <button @ref="btnReferences[iCopy]" @onclick="(async () => await TestRef(iCopy))"></button>
}

@code{
  private List<ElementReference> btnReferences = new List<ElementReference>();

  protected override async Task OnInitializedAsync()
  {
    for(int i = 0; i < 5; i++)
    {
      btnReferences.Add(new ElementReference());
    }
  }

  public async Task TestRef(int i)
  {
    await JSRuntime.InvokeVoidAsync("console.log", testref[i].Id);
  }
}

As Brian already said, @ref needs ElementReference (or component type): string is not a valid type. @onclick meets the same issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM