[英]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.