javascript - 自定义 litelement 选择未正确重新渲染
问题描述
我用 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
作为属性。在第一次渲染时,一切正常。呈现所有选项,并且选择的值反映在选择中。但是,如果我更改selected
它似乎不会更新所选选项。如果我使用 dev-tools 检查元素,则selected
属性设置正确,但如果我开始查询元素的值,它会返回错误的值。
我尝试的一件事是id
在呈现选择后通过开发工具向元素添加一个属性。如果我随后更改selected
on的属性CustomSelect
,则该id
属性会保留在 DOM 中,这告诉我选择没有重新渲染,这就是导致问题的原因,以及为什么它在第一次渲染时起作用。
我已经尝试在选择元素上设置value
andselectedIndex
属性,但它似乎并没有以有意义的方式影响任何东西。
我到处都记录了(从 render() 和 options-map 开始)并且所有输入值都是正确的。
解决方案
我认为,渲染时间和onChange
函数计时冲突的选定属性定义。因此,最好分配一个setTimeout
inonChange
然后它才能正常工作。在下面链接的示例中。当我删除时我也遇到了同样的情况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)
}
推荐阅读
- python - 如何解决错误“object.__new__() 不带参数”?
- c# - 如何在 C# 上读取 .Key 文件?
- shell - 如何让 ffmpeg 在特定时间开始下载流?
- android - Android:将 LiveData 设置为 MutableLiveData
- r - 无法执行 updateR 命令
- postgresql - 如何参数化搜索 jsonb 数组包含?
- c++ - C++中default关键字的用途是什么
- excel - 从公式运行的宏不会复制/粘贴,但通过 vbe 运行它可以正常工作
- spring-mvc - Kotlin 如何使用 assertj 创建自定义断言
- javascript - 在 basic-ftp 上使用上传,其他可能的用途