blazor variable argument passing to onclick function

我的梦境 提交于 2020-02-25 21:26:29

问题


I want to pass the int i into the button onclick function for each list item. I expected the "clickItem" function will receive 0..2 for correspondig list item. But it come out that it always receive 3 as argument. It seems that the variable i in the clickItem(i) is not evaluated at the time of render of the for loop. I have tried changing it to "clickItem(@i)" but it is still the same. What should I do? (I am using blazor server side, .net core 3 preview 5)

        @for (int i = 0; i < 3; i++)
        {
            <li> item @i <button onclick=@(() => clickItem(i))>Click</button> </li>
        }


回答1:


This is a classic, but slightly new in the context of Blazor.

You need to make a copy because otherwise the lambda 'captures' the loop variable. Capturing the copy is OK.

@for (int i = 0; i < 3; i++)
{
    int copy = i;
    <li> item @i <button onclick=@(() => clickItem(copy))>Click</button> </li>
}



回答2:


I tried this, and it worked. Hope it seems helpful to you.

 @foreach (var item in ListOfUser)
            {
                <tr>
                    <td>@item.FirstName</td>
                    <td>
                        <button @onclick="(() => GetDetail(item.UserId)) "> Click</button>
                    </td>
                </tr>
            }


来源:https://stackoverflow.com/questions/56425558/blazor-variable-argument-passing-to-onclick-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!