如何在Blazor中调用子组件的方法

时间:2020-03-20 13:27:58

标签: blazor blazor-server-side

我有Foo.razor

@foreach (var item in items) {
  <p>@item</p>
}

@code {
  private List<string> items = new List<string>();

  public void Append(string item) => items.Add(item);
}

如果我有Bar.razor

<Foo/>

@code {
  public void SomeMethod() {
    ...
  }
}

如何从Append("something")呼叫SomeMethod()

1 个答案:

答案 0 :(得分:0)

下面是使用@ref属性的示例。 @ref提供了一种引用组件实例的方法。请参阅:Blazor Components

Foo

@foreach (var item in items)
{
    <p>@item</p>
}

@code {
    private List<string> items = new List<string>();

    public void Append(string item) =>items.Add(item);

    public void Refresh()
    {
        this.StateHasChanged(); //To refresh component after we have added items
    }
}

酒吧

<Foo @ref="foo"/>

<button class="btn btn-primary" @onclick="SomeMethod">Add items</button>

@code {

    Foo foo;

    public void SomeMethod()
    {
        foo.Append("item1");
        foo.Refresh();
    }

}

注意:

The component variable is only populated after the component is rendered and its output includes the component's element. Until that point, there's nothing to reference. To manipulate components references after the component has finished rendering, use the OnAfterRenderAsync or OnAfterRender methods.