【发布时间】:2018-07-06 13:15:13
【问题描述】:
我正在尝试建立从子元素到其父元素中的组件的引用。我希望能够通过在 init() 函数中调用 this.el.parentEl.components['parent'] 来引用它,但这会返回 undefined。
其他测试用例工作正常: 1. 从父组件引用子组件在父组件中工作正常。 2.从html下面的代码sn-p引用父组件。 3. html下面的代码sn-p从子元素引用父组件。
这是生命周期的问题吗?在这种情况下,为什么孩子和父母之间存在差异?
<script src="https://aframe.io/aframe/dist/aframe-master.min.js"></script>
<script>
AFRAME.registerComponent('parent', {
multiple: false,
init: function () {
this.child = this.el.children[0].components['child']
console.log("child component: ", this.child); //This works
}
})
AFRAME.registerComponent('child', {
multiple: false,
init: function () {
this.parent = this.el.parentEl.components['parent']
console.log("parent component: ", this.parent); //Undefined
}
})
</script>
<a-scene>
<a-entity parent>
<a-entity child></a-entity>
</a-entity>
</a-scene>
<script>
var parent = document.querySelector('[parent]').components.parent
console.log("parent component from below: ", parent); //This works
var parentfromchild = document.querySelector('[child]').parentEl.components['parent']
console.log("parent from child from below: ", parentfromchild); //This works
</script>
【问题讨论】:
-
我推荐使用 Glitch 提供一个可执行的例子来说明问题
标签: aframe