当 @state() decorated 属性 更改时,模板不会重新渲染组件
stencil is not rerendeing component when @state() decorated property is changed
我今天开始使用模板。以下代码是我项目中的全部内容。 Docs 说,如果用 @state()
修饰的 Component 成员发生变化,组件将重新渲染。
Any changes to a @State() property will cause the components render function to be called again.
但即使是这个简单的事情也行不通。请指教。
import {Component, State} from '@stencil/core';
@Component({
tag: 'my-component',
styleUrl: 'my-component.css',
shadow: true
})
export class MyComponent {
@State() name:string = 'john';
changeName(){
this.name = "Peter";
console.log('inside changeName');
}
render() {
return <div>
<p>{this.name}</p>
<button onClick={this.changeName}>click</button>
</div>;
}
}
当我单击按钮时,inside changeName
会被记录下来,但在视图中看不到对 name
的任何更改。
尝试将您的 onClick 更改为箭头函数:
<button onClick={() => this.changeName()}>click</button>
这保留了 this
的含义以引用您的 class。有关详细信息和示例,请参阅 https://stenciljs.com/docs/templating-jsx/#handling-user-input。
@matthewsteele 的回答是正确的,但您也可以像下面这样定义您的函数以使其工作。
private changeName = () => {
this.name = "Peter";
console.log('inside changeName');
}
在 this 引用上方执行操作仍将保留到 class。
我今天开始使用模板。以下代码是我项目中的全部内容。 Docs 说,如果用 @state()
修饰的 Component 成员发生变化,组件将重新渲染。
Any changes to a @State() property will cause the components render function to be called again.
但即使是这个简单的事情也行不通。请指教。
import {Component, State} from '@stencil/core';
@Component({
tag: 'my-component',
styleUrl: 'my-component.css',
shadow: true
})
export class MyComponent {
@State() name:string = 'john';
changeName(){
this.name = "Peter";
console.log('inside changeName');
}
render() {
return <div>
<p>{this.name}</p>
<button onClick={this.changeName}>click</button>
</div>;
}
}
当我单击按钮时,inside changeName
会被记录下来,但在视图中看不到对 name
的任何更改。
尝试将您的 onClick 更改为箭头函数:
<button onClick={() => this.changeName()}>click</button>
这保留了 this
的含义以引用您的 class。有关详细信息和示例,请参阅 https://stenciljs.com/docs/templating-jsx/#handling-user-input。
@matthewsteele 的回答是正确的,但您也可以像下面这样定义您的函数以使其工作。
private changeName = () => {
this.name = "Peter";
console.log('inside changeName');
}
在 this 引用上方执行操作仍将保留到 class。