自定义文字选择不正确重新渲染

问题描述 投票:2回答:1

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

我尝试的一件事是在渲染选择后通过dev-tools向元素添加id属性。如果我然后更改selected上的CustomSelect属性,那么id属性会持续存在于DOM中,它告诉我,select不会被重新渲染,这就是导致问题的原因,以及为什么它在第一次渲染时工作。

我已经尝试在select-element上设置valueselectedIndex属性,但它似乎没有以有意义的方式影响任何东西。

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

javascript polymer lit-element lit-html
1个回答
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)
} 
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.