自定义 litelement 选择未正确重新渲染

Cap*_*oot 6 javascript polymer lit-element lit-html

我用 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);
Run Code Online (Sandbox Code Playgroud)

我在创建元素时传入options,selectedonChange作为属性。在第一次渲染时,一切正常。渲染所有选项,所选值反映在选择中。但是,如果我更改selected它似乎不会更新所选选项。如果我使用 dev-tools 检查元素,selected属性设置正确,但如果我开始查询元素的值,它返回错误的值。

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

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

我已经记录了所有地方(从 render() 和选项映射开始)并且所有输入值都是正确的。

Hak*_*anC 2

我认为,渲染时间和所选属性定义在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)
} 
Run Code Online (Sandbox Code Playgroud)