3

我希望它只更改 clicked 的类div。目前它将更改所有divs 的类。我已将其编写为 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";
        }
    }
}
4

3 回答 3

2

您可以使用数组而不是一个变量。

@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";
      }
  }
}
于 2020-02-19T08:06:49.617 回答
2

试试下面的代码:

@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; }
}
}

上面代码的结果是:

在此处输入图像描述

自由提问。祝你好运。

于 2020-02-19T09:37:41.563 回答
2

为此行为创建一个组件:

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";
        }
    }
}

您的父组件变为:

父组件.razor

@for (int i = 0; i < 5; i++)
{
    <CustomComponet Value="@i" />
}
于 2020-02-19T14:17:41.013 回答