Blazor - 来自后代的事件回调

时间:2021-07-26 10:08:38

标签: c# blazor

我创建了具有如下结构的测试 blazor 服务器应用程序:

    <parent_component>
      <child1_component/>
    </parent_component>

地点:

    <child1_component>
      <child2_component/>
    </child1_component>

    <child2_component>
      <child3_component/>
    </child2_component>

如何在 parent_component 中接收 child3_component 发送的事件回调? 嵌套组件的结构有意义吗? 它在“真实场景”中有用还是我应该使用其他结构?

1 个答案:

答案 0 :(得分:1)

EventCallback 可由承载声明 EventCallback 的组件的组件处理。

换句话说,在你的结构中 child3 的事件可以被 child2 捕获。

要将事件发送给父级,您有两种选择:

  1. 通过堆栈链接事件,以便父组件最终收到来自子 1 的 EventCallback。

  2. 使用事件广播服务。基本上是在启动时注册并可以注入任何组件的服务。 Child3 将调用“发送”方法将事件发送给监听者。事件广播服务将引发事件。 ParentComponent 需要向广播服务注册,以便它可以侦听相应的事件。

这里有一篇很好的入门文章,介绍了您的情况:

https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/

相关问题