【发布时间】: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