[英]Component not re-rendering when calling function from child
我試圖通過從孩子調用父函數來更改屬性。 這是示例的鏈接。 我假設當從事件中調用函數時,屬性更改會觸發重新渲染,即@click
。 但是是否可以通過將函數傳遞給孩子並調用它來更改屬性並觸發重新渲染?
class ParentComponent extends LitElement {
static get properties() {
return {
value: { type: String, reflect: true }
}
}
constructor() {
super();
this.value = 'value';
}
handleClick(value) {
this.value = value;
}
render() {
return html `
<div>
<p>My Value: ${this.value}</p>
<button @click="${() => this.handleClick('value from parent')}">Parent Button</button>
<child-component
.handleClick="${this.handleClick}"
></child-component>
</div>
`;
}
}
customElements.define('parent-component', ParentComponent);
class ChildComponent extends LitElement {
static get properties() {
return {
handleClick: { type: Function }
}
}
render() {
return html `
<button @click="${() => this.handleClick('value from child')}">Child Button</button>
`;
}
}
customElements.define('child-component', ChildComponent);
單擊子按鈕時, handleClick
具有 ChildComponent 的this
上下文。 如果您使用=>
函數更新 ParentComponent 模板,則會在 ParentComonent 上設置新值。
<child-component
.handleClick="${(value) => this.handleClick(value)}"
></child-component>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.