首页 > 解决方案 > 自定义 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,selectedonChange作为属性。在第一次渲染时,一切正常。呈现所有选项,并且选择的值反映在选择中。但是,如果我更改selected它似乎不会更新所选选项。如果我使用 dev-tools 检查元素,则selected属性设置正确,但如果我开始查询元素的值,它会返回错误的值。

我尝试的一件事是id在呈现选择后通过开发工具向元素添加一个属性。如果我随后更改selectedon的属性CustomSelect,则该id属性会保留在 DOM 中,这告诉我选择没有重新渲染,这就是导致问题的原因,以及为什么它在第一次渲染时起作用。

我已经尝试在选择元素上设置valueandselectedIndex属性,但它似乎并没有以有意义的方式影响任何东西。

我到处都记录了(从 render() 和 options-map 开始)并且所有输入值都是正确的。

标签: javascriptpolymerlit-elementlit-html

解决方案


我认为,渲染时间和onChange函数计时冲突的选定属性定义。因此,最好分配一个setTimeoutinonChange然后它才能正常工作。在下面链接的示例中。当我删除时我也遇到了同样的情况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)
} 

推荐阅读