Blazor 突出显示选定的表格行

Sea*_*ean 2 css html-table razor .net-core blazor

我的 blazor 项目中有下表渲染:

<table class="table table-bordered accountTable @HighlightSelected" >
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
    @if (Accounts != null) 
    {
        @foreach (var account in Accounts)
        {
            <tr @onclick="@(() => ReturnRowData(account))"> 
                <td >@account.Id</td>
                <td >@account.Name</td>
            </tr>
        }
    }
    else
    {
        <p>No accounts to display...</p>
    }

    </tbody>
</table>

@code{
  [Parameter]
    public List<Account> Accounts { get; set; }

    [Parameter]
    public EventCallback<Account> OnRowClicked{get;set;}
    public string HighlightSelected = "normal";
public async void ReturnRowData(Account account)
{
    HighlightSelected = "highlight";
    await OnRowClicked.InvokeAsync(account);
}
}
Run Code Online (Sandbox Code Playgroud)

当单击此表上的一行时,它会将所选行数据返回到我的索引页以供其他函数使用。我在这里尝试做的是向所选行添加新的背景颜色。

表中的参数@HighlightSelected是一个字符串变量,我用它来替换我想要的CSS更改。但是,CSS 更改会添加到每一行,而不仅仅是所选的单个行。

在我的 css 中,我尝试了针对我想要的特定 td 的不同组合,但它总是会导致整个表格突出显示。示例为

.highlight table tbody tr.highlight td {
    background-color: red;
} 
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

我知道这是可以做到的,javascript但如果可能的话,我想不惜一切代价避免这种情况。

Ben*_*973 6

每当我使用列表时,我经常创建一个单独的实例以进行选择和比较。

@page "/accounts"


<table class="table table-bordered accountTable">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        @if (AccountsList != null)
        {
            @foreach (var account in AccountsList)
            {
                string colorClass= (account == SelectedAccount) ? "MyHighlightClass" : "";
                <tr class="@colorClass" style="color:navy; cursor:pointer; text-decoration:underline" @onclick="() => { ReturnRowData(account); SelectedAccount = account; }">
                    <td>@account.Id</td>
                    <td>@account.Name</td>
                </tr>
            }
        }
        else
        {
            <p>No accounts to display...</p>
        }

    </tbody>
</table>
@if (SelectedAccount.Id != 0)
{
    <h3>Selected account #@SelectedAccount.Id (@SelectedAccount.Name) </h3>
}

@code {
    public class Account
    {
        public int Id;
        public string Name = "";
    }
    [Parameter]
    public List<Account> AccountsList { get; set; } = new List<Account>() {
            new Account(){ Id = 1, Name="John" },
            new Account(){ Id = 2, Name="Jeff" },
            new Account(){ Id = 3, Name="Jane" }
     };
    Account SelectedAccount { get; set; } = new Account();

    void ReturnRowData(Account account)
    {
        // Do data stuff.
    }
}
Run Code Online (Sandbox Code Playgroud)