Blazor 循环、闭包和绑定

Blazor Looping, Closures and Binding

提问人:Steve Moreno 提问时间:5/21/2022 最后编辑:ℍ ℍSteve Moreno 更新时间:8/17/2022 访问量:177

问:

我把它分解成一个简单的例子,即循环浏览一些东西,但将其分解为关卡。我正在内部循环中实例化本地副本,但这似乎不起作用。 当您尝试更改输入中的值时,它会将它们全部更改为计数器变量。

下面是 Blazor Fiddle 中的代码 https://blazorfiddle.com/s/d02wswws


@for (var i = 0; i < levels; i++)
{
    <div>Level @i</div>
    @for (var j = 0; j < stuffPerLevel; j++)            
    {
        int copy = allStuffCounter;
        <input type="text" @bind="stuff[copy]" @bind:event="oninput" />
        <div>@stuff[copy]</div>
        if(allStuffCounter < stuffCounterLimit) allStuffCounter++;
    }
}

@code
{
  string[] stuff = {"some stuff 1", ... ,"some stuff 20"};
                    
  int allStuffCounter = 0;
  int levels = 3;
  int stuffPerLevel = 4;
  int stuffCounterLimit = 11;
}
C# 闭包 Blazor

评论

1赞 Kirk Woll 5/21/2022
虽然 BlazorFiddle 很好,但你应该在问题本身中包含代码的相关部分。
0赞 Steve Moreno 5/22/2022
是的。我应该有。谢谢。

答:

0赞 enet 5/22/2022 #1

复制并测试...

@for (var i = 0; i < levels; i++)
{
    <div>Level @i</div>

    @for (var j = 0; j < stuffPerLevel; j++)
    {
         int copy = allStuffCounter;

        <input @bind="stuff[copy]" @bind:event="oninput" type="text" />

        <div>@stuff[copy]</div>
        allStuffCounter++;

    }

}

@code
{
    string[] stuff = { "some stuff 1", "some stuff 2", "some stuff 3", "some stuff 4",
        "some stuff 5", "some stuff 6","some stuff 7","some stuff 8","some stuff 9",
        "some stuff 10","some stuff 11","some stuff 12","some stuff 13","some stuff 14",
        "some stuff 15","some stuff 16","some stuff 17","some stuff 18","some stuff 19", "some stuff 20" };


    int allStuffCounter = 0;
    int levels = 3;
    int stuffPerLevel = 4;
    // Superfluous...
   // int stuffCounterLimit = 11;

    protected override void OnAfterRender(bool firstRender)
    {
        allStuffCounter=0;
    }
}