首页 > 解决方案 > 在Javascript中更改模板字符串中的复选框的三元代码

问题描述

我正在使用聚合物和发光元素。在渲染函数中,我有一个模板字符串,如下所示:

render() {
    this.todoItem = JSON.parse(this.todoItem);
    return html`
      <li>
        ${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
        <input
          type="checkbox"
          checked="${this.todoItem.done} ? 'true' : 'false'"
          @click="${this.changeStatus}"
        />
      </li>
    `;
  }

我知道这行不通,因为基于几个stackoverflow答案,您设置的任何checked等于的值都会将其标记为已检查。

如果我这样做:

<input type="checkbox" ${this.todoItem.done} ? 'checked' : ''" @click="${this.changeStatus}"/>

我收到一个错误

TypeError:无法在“TreeWalker”上设置“currentNode”属性:提供的值不是类型

标签: javascriptecmascript-6polymerlit-element

解决方案


遵循文档后,我找到了答案:我不得不使用html https://lit-element.polymer-project.org/guide/templates。以下代码有效。

render() {
    this.todoItem = JSON.parse(this.todoItem);
    return html`
      <li>
        ${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
        ${this.todoItem.done
          ? html`
              <input type="checkbox" checked @click="${this.changeStatus}" />
            `
          : html`
              <input type="checkbox" @click="${this.changeStatus}" />
            `}
      </li>
    `;
  }

更新

render() {
    this.todoItem = JSON.parse(this.todoItem);
    return html`
      <li>
        ${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
        ${html`
          <input type="checkbox" ?checked="${this.todoItem.done}" @click="${this.changeStatus}" />
        `}
      </li>
    `;
  }

更新 V2

render() {
    this.todoItem = JSON.parse(this.todoItem);
    return html`
      <li>
        ${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
        <input type="checkbox" ?checked="${this.todoItem.done}" @click="${this.changeStatus}" />
      </li>
    `;
  }

推荐阅读