从 this.el 遍历到 parentEl 返回 undefined,但反向返回元素



我正在尝试建立从子元素到其父元素中组件的引用。 我希望能够通过在 init(( 函数中调用this.el.parentEl.components['parent']来引用它,但这返回未定义。

其他测试用例工作正常: 1. 从父组件引用子组件在父组件中工作正常。 2. 从 html 下面的代码片段中引用父组件。 3. 从 html 下方的代码片段中的子元素引用父组件。

这是生命周期的问题吗? 为什么在这种情况下,孩子和父母之间有区别?

<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>

调用init时,父级尚未初始化。场景从子项加载到父项。等待场景加载 监听loaded事件:如何检测场景何时加载到A-Frame?

最新更新