blazor变量参数传递给onclick函数 [英] blazor variable argument passing to onclick function

查看:873
本文介绍了blazor变量参数传递给onclick函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将int i传递给每个列表项的按钮onclick函数.我希望"clickItem"函数的对应列表项将收到0..2.但是事实证明,它总是接受3作为参数.似乎在渲染for循环时未评估clickItem(i)中的变量i.我尝试将其更改为"clickItem(@i)",但仍然相同.我该怎么办? (我正在使用blazor服务器端,.net core 3预览5)

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

推荐答案

这是经典的游戏,但在Blazor的上下文中有点新.

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

您需要进行复制,否则lambda会捕获"循环变量.捕获副本就可以了.

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

这篇关于blazor变量参数传递给onclick函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆