首页 > 解决方案 > 如何访问子组件中的元素?

问题描述

我有一个组件,它使用来自<another-component>. 我试图<span>通过调用this.shadowRoot.getElementById('title')来获取<another-component>它,它总是返回null:

  render() {
    return html`
      <another-component>
        <h2 slot="header">
          <span id="title"></span>
        </h2>
        <div slot="footer">
          ${this.renderFooter()}
        </div>
      </another-component>
    `;
  }

有任何想法吗?

标签: javascriptweb-componentlit-element

解决方案


经过一番挖掘,我发现这是设计使然。如果我错了,请纠正我。基本上,您只能访问定义它的影子根下的 DOM 元素,无论它是否在 a 中<slot>

例如,假设在您的主组件中,您有一个组件 A,其中包含一个带有 ID 的元素:

// main component's render
<a>
  <p id="title"></p>
</a>

组件 A 使用组件 B,并将其插槽内容映射到组件 B 中的另一个插槽:

// component A's render
<b>
  <p slot="header">blabla</p>
  <slot slot="content"></slot>
</b>

A 和 B 都不能通过 访问元素shadowRoot.getElementById。只有主组件才能通过 ID 获取元素。


推荐阅读