【问题标题】:how do I declare additional property for React class component?如何为 React 类组件声明附加属性?
【发布时间】:2019-06-06 09:49:37
【问题描述】:

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

export interface ComponentProps {
    propName: string
}

interface ComponentState {
    stateName: number
}

class myComponent extends React.Component<ComponentProps, ComponentState> {
...
}

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

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

[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;

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

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

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

    将您的班级更改为:-

    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>;
        }
    }
    

    希望对你有帮助,

    干杯!!

    【讨论】:

    • 谢谢。我从不认为 customProperty 是类级别的属性,因为它以 this 关键字为前缀。我学到了新东西。
    • TypeError: 无法添加属性编辑器,对象不可扩展
    【解决方案2】:

    你可以在类中声明它:

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

    【讨论】:

    • 感谢您的快速帮助,但提示新错误:[ts] Property 'customProperty' has no initializer 并且未在构造函数中明确分配。 [2564],我该如何解决?
    • 我想我只需要设置一个默认值,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 2022-01-17
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2017-02-12
    • 1970-01-01
    相关资源
    最近更新 更多