javascript - 使用 typescript 在 react 中使用状态值时出现错误

标签 javascript reactjs typescript

在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/

相关文章:

javascript - DRY - 如何制作 2 个将不同表放入 1 个 GET 函数的 GET 函数

javascript - 如何在单击时更改 ListItem 的样式?

angular - Ionic 4 自定义组件

javascript - 无法为带有字符串作为参数的 Angular 组件创建构造函数

javascript - IE6 丢失查询字符串

javascript - 在 setInterval 中使用 += 连续递增变量时出现问题

javascript - GatsbyJS 在从其他组件呈现 GraphQL 查询时出现问题

typescript - 我可以覆盖 TypeScript 接口(interface)中的键吗?

javascript - 助手字符串中的 Handlebars 模板标签

reactjs - React-如何获取 blob SAS URL 或 SAS token ?