如何为 React 类组件声明附加属性?

sea*_*ful 9 typescript reactjs

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

export interface ComponentProps {
    propName: string
}

interface ComponentState {
    stateName: number
}

class myComponent extends React.Component<ComponentProps, ComponentState> {
...
}
Run Code Online (Sandbox Code Playgroud)

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

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

[ts] 类型“MyComponent”上不存在属性“customProperty”。[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;
Run Code Online (Sandbox Code Playgroud)

小智 9

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

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

将您的班级更改为:-

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>;
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助,

干杯!