问题:有没有办法在不触发其功能的情况下将属性更改传播到子元素render
?目前,当我更新父级中的属性时,switchViewModeHandler
它会触发对子级的重新渲染。
用例:将父级切换到“编辑”模式也应该为其所有子级切换相同。
疑问:我应该使用自定义事件吗?问题是它将是一个复杂的嵌套元素网络,其中的事件很快就会变得难以调试(Polymer 已经遇到过这个问题)。
设置:父元素:
class ParentElement extends LitElement {
@property() viewMode;
constructor() {
this.viewMode = ViewMode.editable;
}
static get properties() {
return {
viewMode: { type: String, reflect: true },
};
}
private switchViewModeHandler(event: MouseEvent): void {
this.viewMode =
(this.viewMode === ViewMode.editing) ? ViewMode.editable : ViewMode.editing; // update my own edit mode
const options: HTMLElement[] = (Array.from(this.children) as HTMLElement[]);
options.forEach((item: HTMLElement) => {
item.viewMode = this.viewMode;
});
}
render() {
return html`
<p>parent</p><label class="switch-wrapper">toggle edit mode
<input type="checkbox"
?checked="${this.viewMode === ViewMode.editing}"
@click="${
(event: MouseEvent): void => this.switchViewModeHandler(event)
}"
/>
</label>
<slot></slot><!-- child comes from here -->
`;
}
}
子元素:
class ChildElement extends LitElement {
@property() viewMode;
constructor() {
super();
this.viewMode = ViewMode.editable;
}
static get properties() {
return {
viewMode: { type: String, reflect: true },
};
}
render() {
console.log('child render() called');
return html`
<div class="viewer">child viewer</div>
<div class="editor mode-${this.viewMode}">child editor</div>
`;
}
}
标记:
<parent-element>
<child-element data-type="special"></child-element
></parent-element>
编辑模式来自一个导入的简单枚举(此处省略):
export enum ViewMode {
readOnly = 'readOnly',
editable = 'editable',
editing = 'editing',
}
这是一个可以玩的 Codesandbox:https ://codesandbox.io/s/v1988qmn75