在react文档中的代码之一中,this.state中定义的值在render()中用作
{this.state.name}
但是当我使用打字稿实现该反应代码时,它给出了如下错误:-
Property 'age' does not exist on type 'Readonly<{}>'.
打字稿中的代码是:-
import * as React from "react";
class App2 extends React.Component{
constructor(props:any)
{
super(props)
this.state = {
age : 0,
name : "rohit"
};
}
public render()
{
return(
<h1>
{this.state.name}
</h1>
)
}
}
export default App2;
答案 0 :(得分:2)
在使用Typescript时,您必须为接受的道具和类的状态提供类型,因此您不应从普通的React.Component
派生(默认为React.Component<{}, {}>
,而应将模板参数声明为prop /状态类型。
这样的步骤应该适合您的情况:
interface MyProps {
something?: string;
}
interface MyState {
age: 0;
name: string;
}
class App2 extends React.Component<MyProps, MyState> {
```