Aura.js闪电组件:从超级/父组件触发嵌套/子组件的方法

Aura.js Lightning Components: Firing a nested/child component's methods from the super/parent component?

本文关键字:组件 嵌套 方法 js Aura      更新时间:2023-09-26

我在与嵌套组件通信时遇到问题。我希望组件能够在嵌套组件的控制器中运行方法.js(或助手)。我已经尝试了两个事件和通过,但没有运气。下面是示例标记:

<!-- myEvent.evt -->
<aura:event type="APPLICATION">
</aura:event>
<!-- super-component -->
<aura:component>
    <aura:registerEvent name="myEventName" type="c:myEvent"/>
    <c:my_Nested_Component />
    <ui:button press="{!fireEvent}"
<aura:component>

//super-component_controller.js
({
  fireEvent: function(component){
    var myEvent = component.getEvent("myEventName");
    myEvent.fire();
    console.log('event fired');
  }
})
------------------------------------------
<!-- nested-component -->
<aura:component>
    <aura:handler name="myEventName" event="c:c:myEvent" action="{!c.gotEvent}" />
<aura:component>

//nested-component_controller.js
({
  gotEvent: function(component, event){
    console.log('received event!');
  }
})

这行不通。我尝试了与超级超级组件上嵌套组件上放置的完全相同的代码,并且效果很好。超级超级组件收到了事件。但是嵌套组件无法做到。我认为这与事件只冒泡有关(尽管文档确实说只有组件事件是这种情况,而不是应用程序事件)。

所以我在网上阅读的另一个选项是使用 .我尝试这样做,但这也不适用于与嵌套组件交谈。

父组件如何导致嵌套组件上的方法触发?

谢谢

这个问题在这里得到了解答: https://salesforce.stackexchange.com/questions/108544/lightning-components-firing-a-nested-child-components-methods-from-the-super-p

问题是我使用的是component.getEvent()而不是应用程序级别事件所必需的$A.get()。此外,注册事件的名称不是从处理程序引用事件的方式,而是使用其实际文件名的方式,如下所示:

//super-component_controller.js
 ({
  fireEvent: function(component){
  var myEvent = $A.get("e.c:myEvent");
  myEvent.fire();
  console.log('event fired');
  }
})
<!-- nested-component -->
<aura:component>
   <aura:handler event="c:myEvent" action="{!c.gotEvent}" />
<aura:component>

谢谢@MohithShrivastava弄清楚这个问题!