【发布时间】:2018-12-07 00:46:58
【问题描述】:
当我对这个问题进行搜索时,我只能找到直接在方法体中某处修改this.state 而不是使用this.setState() 的问题。我的问题是我想在构造函数中设置一个起始状态如下:
export default class Square extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
active: false
};
}
public render() {
...
}
}
应用程序无法启动并出现以下编译错误:
Cannot assign to 'state' because it is a constant or a read-only property
这是因为在React.Component 的定义中我们有:
readonly state: null | Readonly<S>;
所以我不知道该怎么做。 JS 中的官方 react 教程直接赋值给 this.state 并说在构造函数中这样做是可接受的模式,但我不知道如何使用 TypeScript 来做到这一点。
【问题讨论】:
标签: reactjs typescript types