在react文档的其中一段代码中,this.state中定义的值在render()中使用为
{this.state.name}
但是当我使用 typescript 实现该 react 代码时,它给出的错误如下:-
Property 'age' does not exist on type 'Readonly<{}>'.
typescript 中的代码是:-
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;
最佳答案
使用 Typescript 时,您必须为您接受的 props 和类的状态提供类型,因此您不应该从普通 React.Component
派生。 (默认为 React.Component<{}, {}>
但将模板参数声明为您想要的 prop/state 类型。
像这样的 Stg 应该适合您的情况:
interface MyProps {
something?: string;
}
interface MyState {
age: 0;
name: string;
}
class App2 extends React.Component<MyProps, MyState> {
```
关于javascript - 使用 typescript 在 react 中使用状态值时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51378195/