Blazor - 动态生成的按钮 table

Blazor - buttons in dynamically generated table

我的 table 有一个小问题,按钮和 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>

例如 table 的大小为 P24,无论我按下哪个按钮,位置始终为 P25,我想要创建特定单元格时位置的值,但位置似乎在我设置时设置单击按钮,当整个 table 已经创建并且坐标已经结束时。

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

我认为这是使用 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 。就是我。

希望这对您有所帮助...