猿问

自定义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在呈现选择之后通过dev-tools向元素添加属性。如果再更改selectedon上CustomSelect的id属性,则该属性将保留在DOM中,这对我说未重新渲染选择,这是导致问题的原因,以及为什么在第一个渲染上起作用。


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


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


冉冉说
浏览 176回答 2
2回答

扬帆大鱼

我认为,在onChange函数计时冲突上渲染时间和选定的属性定义。因此,最好先分配一个setTimeout,onChange然后它才能正常工作。在下面的链接示例中。删除时,我setTimeout&nbsp;也面临同样的问题。此外,您无需onChange在属性中声明为函数。演示版static get properties()&nbsp; {&nbsp; &nbsp;return {&nbsp; &nbsp; &nbsp; &nbsp; options: { type: Array },&nbsp; &nbsp; &nbsp; &nbsp; selected: { type: String }&nbsp; &nbsp; };}constructor() {&nbsp; &nbsp; super();&nbsp; &nbsp; 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"}];&nbsp; &nbsp; this.selected = 3}render() {&nbsp; &nbsp; return html`&nbsp; &nbsp; &nbsp; &nbsp; <select id="sel" @change="${this.onChange}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ${this.options.map(option => html`&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="${option.value}" ?selected=${this.selected === option.value}>${option.text}</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; `)}&nbsp; &nbsp; &nbsp; &nbsp; </select>&nbsp; &nbsp; &nbsp; &nbsp; <button @click="${this.changeSelected}">Random chage selected option</button>&nbsp; &nbsp; `;}onChange(x){&nbsp;setTimeout(()=>{&nbsp;&nbsp; &nbsp; this.selected = this.shadowRoot.querySelector('#sel').value&nbsp; &nbsp; console.log('Selected -->', this.selected );&nbsp; &nbsp;},300)}changeSelected(){&nbsp; this.selected = (this.options[Math.floor(Math.random() * 6)].value)&nbsp; console.log(this.selected)}&nbsp;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答