我用LitElement创建了一个自定义选择组件:
import { LitElement, html } from 'lit-element';
class CustomSelect extends LitElement {
static get properties() {
return {
options: { type: Array },
selected: { type: String },
onChange: { type: Function }
};
}
constructor() {
super();
this.options = [];
}
render() {
return html`
<select @change="${this.onChange}">
${this.options.map(option => html`
<option value="${option.value}" ?selected=${this.selected === option.value}>${option.text}</option>
`)}
</select>
`;
}
createRenderRoot() {
return this;
}
}
customElements.define('custom-select', CustomSelect);
当我创建元素时,我传入options
,selected
和onChange
作为属性。在第一次渲染时,一切正常。将呈现所有选项,并在select中反映所选值。但是,如果我更改selected
,它似乎不会更新所选的选项。如果我使用dev-tools检查元素,则会正确设置selected
属性,但如果我开始查询元素的值,则返回错误的值。
我尝试的一件事是在渲染选择后通过dev-tools向元素添加id
属性。如果我然后更改selected
上的CustomSelect
属性,那么id
属性会持续存在于DOM中,它告诉我,select不会被重新渲染,这就是导致问题的原因,以及为什么它在第一次渲染时工作。
我已经尝试在select-element上设置value
和selectedIndex
属性,但它似乎没有以有意义的方式影响任何东西。
我已经到处记录(从render()和options-map开始)并且所有输入值都是正确的。
我认为,在onChange
函数上渲染时间和所选属性定义的时间冲突。所以,最好在setTimeout
中分配一个onChange
然后它正常工作。在我的例子下面的链接。当我删除setTimeout
时,我也面临同样的问题。此外,您不需要将onChange
声明为属性的函数。
static get properties() {
return {
options: { type: Array },
selected: { type: String }
};
}
constructor() {
super();
this.options = [{value:1, text:"ben"},{value:2, text:"sen"},{value:3, text:"oo"},{value:4, text:"biz"},{value:5, text:"siz"},{value:6, text:"onlar"}];
this.selected = 3
}
render() {
return html`
<select id="sel" @change="${this.onChange}">
${this.options.map(option => html`
<option value="${option.value}" ?selected=${this.selected === option.value}>${option.text}</option>
`)}
</select>
<button @click="${this.changeSelected}">Random chage selected option</button>
`;
}
onChange(x){
setTimeout(()=>{
this.selected = this.shadowRoot.querySelector('#sel').value
console.log('Selected -->', this.selected );
},300)
}
changeSelected(){
this.selected = (this.options[Math.floor(Math.random() * 6)].value)
console.log(this.selected)
}