从 Blazor 中生成的按钮调用函数 [英] Calling function from generated button in Blazor

查看:43
本文介绍了从 Blazor 中生成的按钮调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试从一些自动生成的按钮调用一个方法,这些按钮是从一些配置中设置的.所以按钮的数量是可配置的.我有如下所示的 blazor 页面.我的问题是,如果我有 3 个按钮并按下一个按钮,则 ButtonClicked 会被正确调用,但索引始终为 3 - forint i 的结束值 -陈述.我当然希望将按钮的索引传递给函数.一个明显的解决方案是在我自己的组件中包装一个按钮,然后该按钮将接受一个索引参数,这可以传递给一个 buttonclicked 事件,但是如何在不制作我自己的按钮组件的情况下使下面的代码工作?

@inject Navigator 导航器<div class="chooseDiv">@for (int i = 0; i < Buttons.Count; i++){<button type="button" class="btn btn-primary btn-lg" style="margin:10px" onclick="@((ui) => ButtonClicked(i))">@Buttons[i]}

@职能 {[参数] List按钮{得到;放;} = new List() { "你忘了声明你的按钮" };私有无效ButtonClicked(整数索引){Console.WriteLine("按钮点击索引:" + index);navigator.CurrentResult = 索引;navigator.Next();}}

解决方案

我想你应该在循环中添加一个局部变量,如下所示:

@for (int i = 0; i }

这是标准的 C# 行为,与 Blazor 无关,其中 lambda 表达式 @((ui) => ButtonClicked(i)) 可以访问变量而不是其值.你必须定义一个局部于你的循环的变量,否则你的 lambda 表达式总是调用 ButtonClicked(i) 并且当循环结束时 i 等于 3.

希望这有帮助...

I'm currently trying to call a method from some autogenerated buttons, that are set up from some configuration. So the number of buttons is configurable. I have the blazor page as shown below. My problem is that if I have 3 buttons and I press one then ButtonClicked is called correctly, but the index is always 3 - the end value of int i for the for-statement. I of course want the index of the button to be passed to the function. One obvious solution would be to wrap a button in my own component that would then take an index-parameter and this could be passed along to a buttonclicked event, but how can I make the code below work without making my own button component?

@inject Navigator navigator

<div class="chooseDiv">
    @for (int i = 0; i < Buttons.Count; i++)
    {
        <button type="button" class="btn btn-primary btn-lg" style="margin:10px" onclick="@((ui) => ButtonClicked(i))">@Buttons[i]</button>
    }
</div>

@functions {
    [Parameter] List<string> Buttons { get; set; } = new List<string>() { "You forgot to declare your buttons" };

    private void ButtonClicked(int index)
    {
        Console.WriteLine("Button clicked with index:" + index);
        navigator.CurrentResult = index;
        navigator.Next();
    }
}

解决方案

I guess you should add a local variable to your loop as follows:

@for (int i = 0; i < Buttons.Count; i++)
    {
        var local = i;
        <button type="button" class="btn btn-primary btn-lg" style="margin:10px" onclick="@((ui) => ButtonClicked(local))">@Buttons[i]</button>
    }

This is a standard C# behavior, not related to Blazor, where the lambda expression @((ui) => ButtonClicked(i)) has access to a variable and not to its value. You've got to define a variable which is local to your loop, otherwise your lambda expression always calls ButtonClicked(i) and i equals 3 when the loop ends.

Hope this helps...

这篇关于从 Blazor 中生成的按钮调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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