仅为选定的 div 更改 class

Change class for selected div only

我希望它只更改单击的 div 的 class。目前它将更改所有 div 的 class。我已将其编写为 Blazor 组件。

@for (int i = 0; i < 5; i++)
{
    <div class="@divClass" @onclick="_ => ChangeDivClass()">@i</div>
}

@code 
{    
    String divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = String.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}

您可以使用数组代替一个变量。

@for (int i = 0; i < divClass.Length; i++)
 {
   var index = i;
   <div class="@divClass[i]" @onclick="_ => ChangeDivClass(index)">@i</div>
 }

@code 
 {    
   string[] divClass= new string[5];

   private void ChangeDivClass(int i)
    {
     if (divClass[i] == "red")
      {
        divClass[i] = String.Empty;
      }
     else
      {
        divClass[i] = "red";
      }
  }
}

试试下面的代码:

@if (items != null)
{
    @foreach (var item in items)
    {
        <div class="@RenderDomClass(item.Id)" @onclick="_ => ChangeColor(item.Id)">@item.Id</div>
    }
}

@functions{
    //Instead of these Mock data you should load your own data
    IList<Foo> items = new List<Foo>()
         {
            new Foo { Id =1, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =2, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =3, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =4, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =5, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =6, DomClasses=new List<string>(){string.Empty}},

        };

private void ChangeColor(int id)
{
    var domClasses = items.SingleOrDefault(item => item.Id == id).DomClasses;
    if (domClasses.Contains("red"))
    {
        domClasses.Remove("red");
    }
    else
    {
        domClasses.Add("red");
    }

    RenderDomClass(id);
}

private string RenderDomClass(int id)
{
    var domClass = string.Empty;
    var domClasses = items.SingleOrDefault(item => item.Id == id).DomClasses;
    if (domClasses.Count > 0)
    {
        foreach (var item in domClasses)
        {
            domClass += $" {item}";
        }
    }

    return domClass;
}


public class Foo
{
    public int Id { get; set; }
    public List<string> DomClasses { get; set; }
}
}

以上代码的结果为:

有空提问。祝你好运。

为此行为创建一个组件:

CustomComponent.razor

<div class="@divClass" @onclick="ChangeDivClass">@Value</div>
@code 
{    
    [Parameter]
    public int Value;

    string divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = string.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}

您的父组件变为:

ParentComponent.razor

@for (int i = 0; i < 5; i++)
{
    <CustomComponet Value="@i" />
}