自定义litelement选择未正确重新呈现

时间:2019-04-25 21:45:38

标签: 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);

我在创建元素时将optionsselectedonChange作为属性传递。在第一个渲染中,一切正常。呈现所有选项,并且所选值反映在选择中。但是,如果我更改selected,则似乎没有更新所选的选项。如果我使用dev-tools检查该元素,则selected属性设置正确,但是如果我开始查询该元素的值,它将返回错误的值。

我尝试做的一件事是在呈现选择之后,通过dev-tools向元素添加id属性。然后,如果我更改selected上的CustomSelect属性,则id属性将保留在DOM中,这对我来说表示未重新呈现选择内容,这是导致问题的原因,以及为什么它可以在第一个渲染上工作。

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

我已经登录了所有地方(从render()和options-map开始),并且所有输入值都是正确的。

2 个答案:

答案 0 :(得分:0)

我认为,onChange上的渲染时间和选定的属性定义会影响时间冲突。因此,最好在setTimeout中分配一个onChange,然后它才能正常工作。在下面的链接示例中。删除setTimeout时,我也遇到了同样的情况 另外,您无需在属性中将onChange声明为函数。

Demo

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)
} 

答案 1 :(得分:0)

工作示例:

https://stackblitz.com/edit/litelement-testt-csgkmc

使用重复指令固定。

import { repeat } from 'lit-html/directives/repeat';

${repeat(this.sortedRows, e => e, row => html`
    <tr>
    ${row.map((cell, index) => html`
      <td>${this.onRenderCell(cell, index, row)}</td>
    `)}
    </tr>
`)}

https://github.com/Polymer/lit-element/issues/805#issuecomment-530461555

相关问题