Polymer 2.0 access a parent component from child component

。_饼干妹妹 提交于 2019-12-20 05:37:54

问题


I have a nested component, what is the Polymer way to travel up the DOM or component tree in this case.

<parent-component>
  <some-component>
    <component-i-am-starting-from></<component-i-am-starting-from>
  </some-component>
 <some-other-component>
 </some-other-component>
</parent-component>

I'd like to be at a deep nested component and reference any of the parent components and their models or trigger an event inside one of them. Bonus if I can access sibling components, etc.

Traveling down was easy enough with

this.$.idOfChildComponent.event()

I have tried dispatchEvent, domHost, shadowRoot, can't seem to get any further up the component tree then the direct parent or get an error back that something is undefined, is not a function, etc.

Is there a way like React to pass a reference down as a property. The docs do not seem to be helpful nor scouring the internet.

Thanks!

update

So I am not sure if this is the correct way but it works ok calling a parent function from a child function.

<parent-component id="parentComponent">
  <some-component>
    <component-i-am-starting-from></<component-i-am-starting-from>
  </some-component>
 <some-other-component>
 </some-other-component>
</parent-component>

componentIAmStartingFromFunc(){
 document.getElementById('parentElement').parentElementFunc()
}

However does not seem to work for siblings?

** Update ** I essentially did the same the to call the sibling event by calling the parent from one of its children, and then sent out a trigger to the sibling which is also a child component.


回答1:


Calling a parent function from child ;

child-component.html (polymer 2.x)

this.dispatchEvent(new CustomEvent('upway-func', {detail: {op:"Optionally I can send some data"}}));

child-component.html (polymer 1.x)

 this.fire('upway-func', {detail: {op:"Optionally I can send some data"}});

parent-component.html

...
<child-component on-upway-func='_someFunction'></child-component>

...
_someFunction(d){
  console.log(d.detail.op); // "Optionally I can send some data"
 }

Here this link for more detail




回答2:


Have you tried using this.parentElement?

Ask yourself: if I were a span in a div, how would I get to the div?

If you want to find a particular element in the ancestor chain by selector, you can use .closest() in good browsers or https://github.com/jonathantneal/closest

The message system mentioned in another answer can work but doesn't help you with positional relationship traversing which I assume your question was requiring. Passing ids and/or objects down can be used with messages in some cases.



来源:https://stackoverflow.com/questions/47820353/polymer-2-0-access-a-parent-component-from-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!