[英]Component not re-rendering when calling function from child
I am trying to change the property by calling the parent function from the child.我试图通过从孩子调用父函数来更改属性。 Here is the link to an example.
这是示例的链接。 I assume that the property change triggers re-render when the function called from the event ie
@click
.我假设当从事件中调用函数时,属性更改会触发重新渲染,即
@click
。 But is it possible to change the property and trigger re-render by passing the function to the child and calling it?但是是否可以通过将函数传递给孩子并调用它来更改属性并触发重新渲染?
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);
When the child button is clicked handleClick
has a this
context of the ChildComponent.单击子按钮时,
handleClick
具有 ChildComponent 的this
上下文。 If you update the ParentComponent template with an =>
function the new value gets set on the ParentComonent.如果您使用
=>
函数更新 ParentComponent 模板,则会在 ParentComonent 上设置新值。
<child-component
.handleClick="${(value) => this.handleClick(value)}"
></child-component>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.