如何为 React 类组件声明其他属性



我用TypeScript重写了我的React项目。 现在我知道如何为类组件声明属性接口和状态接口,像这样简单:

export interface ComponentProps {
    propName: string
}
interface ComponentState {
    stateName: number
}
class myComponent extends React.Component<ComponentProps, ComponentState> {
...
}

但是当我在组件DidMount()生命周期中执行某些操作时会出现错误:

componentDidMount() {
    this.customProperty = 26;  // here I could save an id returned by setInterval to cancel it in the componentWillUnmount() for example.
}

[ts] 属性 'customProperty' 在类型"MyComponent" 上不存在。[2339]我该怎么做才能正确声明其他属性,而不仅仅是简单地使错误静音。

我已经学会了打字稿的基础知识。

import React, { Component } from 'react';
export interface CheckoutProps {
    total: number;
    customer: string;
}
interface State {
    isChecking: boolean;
}
class Checkout extends Component<CheckoutProps, State> {
    state = {
        isChecking: false
    };
    componentDidMount() {
    this.customProperty = 'sean';
    }
    render() {
        return <div>hello</div>;
    }
}
export default Checkout;

类级别属性可以在类声明之后定义,

它们可以在声明时或在构造函数中初始化。

将您的班级更改为:-

class Checkout extends Component<CheckoutProps, State> {
    customProperty:string=''; //Here,you can define your class level properties
    state = {
        isChecking: false
    };
    componentDidMount() {
    this.customProperty = 'sean';
    }
    render() {
        return <div>hello</div>;
    }
}

希望这有帮助,

干杯!!

您可以在类中声明它:

class myComponent extends React.Component<ComponentProps, ComponentState> {
     private customProperty: string = '';
     componentDidMount() {
        this.customProperty = 'sean';
     }
}

最新更新