嵌套组件如何在 Stencil 中工作?

How Nested Components Works in Stencil?

我在 Stencil 的官方文档中找到了这些片段。

我无法理解 my-embedded-component 如何在 my-parent-component 中访问不提供子组件的路径。谁能帮我理解这个概念?

子组件

import { Component, Prop } from '@stencil/core';

@Component({
  tag: 'my-embedded-component'
})
export class MyEmbeddedComponent {
  @Prop() color: string = 'blue';

  render() {
    return (
    <div>My favorite color is {this.color}</div>
    );
  }
}

父组件

import { Component } from '@stencil/core';

@Component({
  tag: 'my-parent-component'
})
export class MyParentComponent {

  render() {
    return (
      <div>
        <my-embedded-component color="red"></my-embedded-component>
      </div>
    );
  }
}

没有路径。建立关系是因为元素嵌套在 HTML 源中。

在普通的 HTML 以下结构中,div 中的一个段落在 DOM 中创建了一个 parent/child 关系:

<div>
    <p>Hello World!</p>
</div>

您在 MyParentComponent 的模板中使用 my-embedded-component 做同样的事情。在页面上呈现父组件之前,初始 HTML 源类似于:

<my-parent-component>
    <div>
        <my-embedded-component color="red"></my-embedded-component>
    </div>
</my-parent-component>

然后对其进行编译以应用各个组件中描述的行为。

@Component 装饰器中的 tag 属性 定义了您在 HTML.

中使用的自定义标签的名称

当 Angular 编译器读取您的初始 HTML 源代码时,它会查找必须转换的指令(标记、属性等)。当这些指令嵌套时,它会创建隐式关系:父级可以使用子级的某些属性,反之亦然。