为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

冉冉说 2021-05-04 21:37:23
我使用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开始),并且所有输入值都是正确的。
查看完整描述

2 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

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


查看完整回答
反对 回复 2021-05-13
  • 2 回答
  • 0 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信