javascript - 如何访问子组件中的元素?
问题描述
我有一个组件,它使用来自<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>
`;
}
有任何想法吗?
解决方案
经过一番挖掘,我发现这是设计使然。如果我错了,请纠正我。基本上,您只能访问定义它的影子根下的 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 获取元素。
推荐阅读
- sql - 参考期前 1 年和参考期后 1 年使用糖果的持续时间
- bash - 如何在 bash 脚本中正确运行 gobuster?(无效的 URL 空格错误)
- interpreted-language - 编译器和解释器优先
- javascript - 将组件拖到Vue中的特定目标
- java - 在java,android中设置为铃声/通知声音
- python - Selenium :单击 div 内的链接
- java - ThreadPoolExecutor 如何从 ThreadPool 中分配一个线程?
- powershell - 从特定 VM 获取快照的名称?
- javascript - 如何在加载 dom 之前验证用户令牌?
- if-statement - 赛普拉斯:如果不存在,我如何检查元素是否存在而不通过测试?