[英]How to access elements in a child component <slot>?
I have a component which uses named slots from <another-component>
.我有一个组件,它使用来自
<another-component>
命名插槽。 I was trying to get the <span>
by calling this.shadowRoot.getElementById('title')
in <another-component>
, it always returns null:我试图通过在
<another-component>
调用this.shadowRoot.getElementById('title')
来获取<span>
<another-component>
,它总是返回 null:
render() {
return html`
<another-component>
<h2 slot="header">
<span id="title"></span>
</h2>
<div slot="footer">
${this.renderFooter()}
</div>
</another-component>
`;
}
Any ideas?有任何想法吗?
After some digging, i found this is by design.经过一番挖掘,我发现这是设计使然。 Please correct me if i'm wrong.
如果我错了,请纠正我。 Basically, you can only access a DOM element under a shadow root where it's defined no matter if it's in a
<slot>
or not.基本上,无论是否在
<slot>
,您都只能访问定义它的影子根下的 DOM 元素。
For example, let's say in your main component, you have a component A with an element with an ID:例如,假设在您的主组件中,您有一个组件 A,其中包含一个带有 ID 的元素:
// main component's render
<a>
<p id="title"></p>
</a>
Component A uses component B, and maps its slot content to another slot in component B:组件 A 使用组件 B,并将其插槽内容映射到组件 B 中的另一个插槽:
// component A's render
<b>
<p slot="header">blabla</p>
<slot slot="content"></slot>
</b>
Neither A nor B can access the element via shadowRoot.getElementById
. A 和 B 都不能通过
shadowRoot.getElementById
访问元素。 Only the main component can get the element by ID.只有主组件可以通过 ID 获取元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.