【问题标题】:How to call a method of the child component in Blazor如何在 Blazor 中调用子组件的方法
【发布时间】:2020-03-20 13:27:58
【问题描述】:

我有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() {
    ...
  }
}

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

【问题讨论】:

标签: blazor blazor-server-side


【解决方案1】:

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

@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.

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 2021-06-10
    • 2022-12-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2020-06-15
    • 2021-09-24
    相关资源
    最近更新 更多