【发布时间】:2021-10-05 15:33:27
【问题描述】:
我不明白lit 的 Web 组件架构中的反应性概念。从其他框架中,我假设以下示例将毫无问题地更新,但它不适用于lit。
我可以看到子组件render 方法仅在最初被调用,而在我单击按钮后不再被调用。但即使我通过Web Components DevTools 手动调用它,它也不会以新状态重新渲染。
我必须改变什么才能让它工作?
父组件:
import {LitElement, html} from 'lit';
import {customElement, property} from 'lit/decorators.js';
import './show-planets';
@customElement('lit-app')
export class LitApp extends LitElement {
addPlanet() {
this.planetsParent.push('Pluto')
console.log('this.planetsParent', this.planetsParent)
}
@property({type: Array}) planetsParent = ['Mars'];
render() {
return html`
<button @click="${this.addPlanet}">click</button>
<show-planets .planetsChild="${this.planetsParent}"></show-planets>
`;
}
}
子组件:
import {LitElement, html} from 'lit';
import {customElement, property} from 'lit/decorators.js';
@customElement('show-planets')
export class ShowPlanets extends LitElement {
@property({type: Array}) planetsChild = ['Pluto'];
render() {
console.log('this.planetsChild', this.planetsChild);
return html`<h1>Planets are: ${this.planetsChild}</h1>`;
}
}
【问题讨论】:
-
与 React 完全一样,Lit 只有在引用发生变化时才能检测到变化。推送到数组对引用没有任何作用,您需要做的是
this.planetsParent = [...this.planetsParent, 'Pluto'];参见此处:lit.dev/docs/components/properties/#haschanged -
你可以像@ChrisG 提到的那样做,或者只是在
addPlanet函数中调用this.requestUpdate()来通知lit 发生了一些变化 -
我们有生命周期方法来执行基于监听器的各种工作。也许这可以帮助你
https://lit-element.polymer-project.org/guide/lifecycle
标签: javascript typescript lit-element lit-html lit