Polymer 2.0从子组件访问父组件 [英] Polymer 2.0 access a parent component from child component
问题描述
我有一个嵌套的组件,在这种情况下,向上移动DOM或组件树的Polymer方法是什么.
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.
有了
下来很容易
this.$.idOfChildComponent.event()
我尝试了dispatchEvent,domHost,shadowRoot,似乎无法再从直接父级到组件树进一步,或者得到错误消息,指出未定义,不是函数等.
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.
是否有类似React的方法将引用作为属性传递下来.这些文档似乎对您没有帮助,也对互联网没有帮助.
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.
谢谢!
更新
所以我不确定这是否正确,但是可以从子函数中调用父函数.
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.
推荐答案
从child调用父函数;
Calling a parent function from child ;
child-component.html(聚合物2.x)
this.dispatchEvent(new CustomEvent('upway-func', {detail: {op:"Optionally I can send some data"}}));
child-component.html(聚合物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
这篇关于Polymer 2.0从子组件访问父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!