如何使用foreach从父组件调用子组件方法 [英] How to call child component method from parent component with foreach

查看:130
本文介绍了如何使用foreach从父组件调用子组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了如何使用@ref属性从父组件调用子组件的方法的示例,但是当我尝试通过foreach循环使用子组件的方法时,只有最后一个呈现的组件的方法被调用,并且不是所有的人.以下是我的组件示例.

I've seen examples of how to call a child component's method from a parent component using the @ref attribute, but when I try to use it with a foreach loop, only the last rendered component's method gets called and not all of them. Below are examples of my components.

父组件:

<button type="button" class="btn btn-link" @onclick="BtnSyncAll_Click">Run<button>

@foreach(var site in Sites)
{
    <Site @ref="SiteView" @Code="@site"></Site>
}

@code {
    protected Site SiteView;
    protected List<string> Sites { get; set; } = new List<string>
    {
        "A00001",
        "A00002"
    };

    protected async Task BtnSyncAll_Click()
    {
        await SiteView.Sync();
    }
}

子组件(Site.razor):

<div>
    <p>@Code>/p>
</div>

@code {
    [Parameter]
    public string Code { get; set; }

    protected async Task Sync()
    {
        await ...
    }
}

推荐答案

您和enet都使事情变得过于复杂...

Both you and enet are overcomplicating things...

最政治上正确"的假装执行的方法可能是创建一个独立的服务,以在必须重新同步时向每个子组件发出信号,并通过DI注入该子组件,但这会花费很多时间,在您的情况下,可能不值得.因此,这里有一个更简单的方法:

The most "politically correct" approach to do what you pretend may be creating an independent service to signal every child component when has to resync, and inject it by means of DI, but this would take too much plumbing for this, and maybe in your case it's not worth it. So here you have a simpler approach:

首先,从组件中删除Sync方法,为此进行更改:

First, remove the Sync method from your component, change it for this:

[Parameter]
public int SyncSignaler { get; set; }


protected override async Task OnParametersSetAsync()
{
    await Task.Delay(300);
    output = $"This is Site: {Code}";
    //StateHasChanged();
}

然后,在父组件上声明一个整数变量,将其传递给子组件,并在每次希望它们刷新时对其进行递增.

Then, declare a integer variable on your parent component, pass it to the childs, and increment it every time you want them to refresh.

在您的父组件中:

@foreach (var site in MySites)
{
    <Site Code="@site.Code" SyncSignaler="@syncIndicator"></Site>
}


@code {
 
    private int syncIndicator = 0;

    protected async Task BtnSyncAll_Click()
    {
        syncIndicator++;
        StateHasChanged();
    }

etc...

请让我知道它是否有效.干杯!

Please, let me know if it worked. Cheers!

这篇关于如何使用foreach从父组件调用子组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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