在 child 个组件中传播一个值

Propagate a value in child components

一个按钮切换 MainComp 中的一个布尔值。 我想在两个嵌套的 child 组件中传播值 。我的真实项目使用第一级 child,它无法更新第二级 child 组件。 但奇怪的是,尝试在 codepen 中复制代码时,我注意到它在第一级也不起作用 child。

https://codepen.io/alfredopacino/pen/eqVGJa?editors=1001

class MainComp extends LitElement {
    constructor() {
        super()
        this.booleanValue = true
    }
    toggleBooleanValue() {
        this.booleanValue = !this.booleanValue
        this.requestUpdate();
    }
    render() {
        return html `
<style>  div {padding: 1em; border:1px solid #000} </style>
<div> main component booleanValue: ${!!this.booleanValue} <button @click=${this.toggleBooleanValue}>toggle</button>
 <child-comp ?booleanValue=${this.booleanValue}></child-comp>
</div>
`
    }
}

class ChildComp extends LitElement {
    constructor() {
        super()
    }
    static get properties() {
        return {
            booleanValue: Boolean
        }
    }
    render() {
        return html `
<style>  div {padding: 1em; border:1px solid green} </style>
<div> child component booleanValue: ${!!this.booleanValue}
<child-2-comp ?booleanValue=${this.booleanValue}></child-2-comp>
</div>
   `
    }
}

class Child_2_Comp extends LitElement {
    constructor() {
        super()
    }
    static get properties() {
        return {
            booleanValue: Boolean
        }
    }
    render() {
        return html `
<style>  div {padding: 1em; border:1px solid red} </style>
<div> child 2 component booleanValue: ${!!this.booleanValue}</div>
   `
    }
}

要在 MainComp 中 booleanValue 触发渲染,您必须将其添加到 MainComp 的属性中:

class MainComp extends LitElement {
  static get properties() {
    return {
      booleanValue: {type: Boolean}
    }
  }
}

请注意 属性 被定义为 {type: Boolean} 而不仅仅是 Boolean 这是 LitElement 知道如何在进行更新时处理 属性 所必需的

Demo

有关更多信息,请查看 LitElement 文档中的这两个指南 https://lit-element.polymer-project.org/guide/properties https://lit-element.polymer-project.org/guide/lifecycle