【发布时间】:2021-01-08 22:00:39
【问题描述】:
我是 stenciljs 的 webcomponents 新手,我正在测试创建一个选择,这个代码的想法是创建和呈现选择:
<rhx-select label-text="A select web component">
<rhx-select-item value="1" text="option 1"/>
<rhx-select-item value="2" text="option 2"/>
</rhx-select>
我遇到的问题是如何获取 Web 组件中的标签?
这是我的代码:
import { Component, h, Prop, } from '@stencil/core';
@Component({
tag: 'rhx-select',
styleUrl: 'select.css',
shadow: true,
})
export class RhxSelect {
@Prop() labelText: string = 'select-rhx';
@Prop() id: string;
@Element() el: HTMLElement;
renderOptions() {
let data = Array.from(this.el.querySelectorAll('rhx-select-item'));
return data.map((e) =>{
<option value={e.attributes.getNamedItem('value').value}>{e.attributes.getNamedItem('text').value}</option>
});
}
render(){
return (
<div>
<label htmlFor={this.id}>
{this.labelText}
</label>
<select id={this.id} class="rhx-select">
{this.renderOptions()}
</select>
</div>
)
}
}
感谢您的宝贵时间。
【问题讨论】:
-
像
<script src="path/to/bundle.js" defer></script>一样简单地添加你的 webcomponents 包。这可以确保在组件初始化之前解析 DOM。 -
这能回答你的问题吗? stackoverflow.com/questions/49786436/…