【问题标题】:Blazor - buttons in dynamically generated tableBlazor - 动态生成的表格中的按钮
【发布时间】:2019-11-01 10:09:45
【问题描述】:

我的表格有一个小问题,按钮和 onclick 工作正常,但是我想通过点击传递的参数没有按我预期的方式工作。

这是代码。

<table class="table-spaced table-responsive">
    <thead>
        <tr>
            <th />
            @for (int i = 1; i <= Plate.PlateType.NumberOfColumns; i++)
            {
                <th class="cell_head">@i</th>
            }
        </tr>
    </thead>
    <tbody>
        @for (int y = 0; y < Plate.PlateType.NumberOfRows; y++)
        {
            <tr>
                <td style="vertical-align:central">
                    @Helper.RowLetters[y]
                </td>
                @for (int x = 1; x <= Plate.PlateType.NumberOfColumns; x++, Position = string.Format("{0:c}{1:d2}", Helper.RowLetters[y], x))
                {
                    if (Plate.Compounds.ContainsKey(string.Format("{0:c}{1:d2}", Helper.RowLetters[y], x)))
                    {
        ---->           <td class="compound"><button type="button" class="compound" @onclick="() => PlateGridClick(Position)" itemprop="@string.Format("{0:c}{1:d2}", Helper.RowLetters[y], x))"/></td>
                    }
                    else
                    {
                        <td class="no_compound" />
                    }
                }
            </tr>
        }
    </tbody>
</table>

表格的大小例如为 P24,无论我按下哪个按钮,位置始终为 P25,我想要创建该特定单元格时的位置值,但是当我单击按钮时,位置似乎已设置,当整个表格已经创建完毕,坐标已经到达终点。

有没有办法在 blazor 中实现与单击事件相同的功能,但将参数存储在按钮中,而不是在单击时获取 Position 参数的当前值?

【问题讨论】:

    标签: c# blazor .net-core-3.0 blazor-server-side


    【解决方案1】:

    我相信这是使用 for 循环的结果。

    试试这个:在你的 for 循环中定义一个局部变量,并将局部变量的值分配给必要的代码。

    示例代码阐明我的意思:

    此循环创建 10 个按钮元素,其值 10 传递给 ShowPosition 方法。无论您单击哪个按钮,值 10 都会传递给 ShowPosition 方法。 10 是 for 循环结束时 i 的值。这是不这样做的方法

     @for (int i = 0; i < 10; i++)
        {
            <button type="button" @onclick="() => ShowPosition(i)">Click</button> 
        }
    

    为了做到这一点,你应该创建一个像下面这样的局部变量

     @for (int i = 0; i < 10; i++)
     {
         var local_i = i;
    
         <button type="button" @onclick="() => ShowPosition(local_i)">Click</button>
            }
    

    现在,每当您单击按钮控件时,都会得到正确的值。

    请搜索完整的答案,并解释 Lambada 方法在用户 Isaac 中的行为方式。就是我。

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 2011-05-13
      相关资源
      最近更新 更多