[英]Migrating from React ES6 to TypeScript: converting (This) to type
I am fairly new to TypeScript, and have been handed an ES6 based react project, and would like to Migrate over to TypeScript for a more integrated state. 我对TypeScript还是相当陌生,并且已经获得了一个基于ES6的react项目,并且希望迁移到TypeScript获得更集成的状态。 Anything following a (this.) seems to break with error (Property "foo" does not exist on Type "bar")
(this。)之后的所有内容似乎都因错误而中断(类型“ bar”上不存在属性“ foo”)
import * as React from 'react';
import { Component } from 'react';
class Clock extends Component {
constructor(props: {}) {
super(props);
this.state = {
date: new Date()
};
}
componentDidMount() {
this.timerId = setInterval(
() => this.tick(), 500
);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
const options = { hour24: false };
return (
<div className="clockDesign">{this.state.date.toLocaleString('en-US', options)}</div>
);
}
}
export default Clock;
My question is this. 我的问题是这个。 How would I go about converting the inline definitions to types within my class statement?
如何将内联定义转换为类语句中的类型?
Declare the fields of your class before assigning them. 在分配课程之前,请声明他们的课程。 For example:
例如:
class Clock extends Component {
private state: { date: Date }
constructor(props: {}) {
super(props);
this.state = {
date: new Date()
};
}
// ...
}
Or if state
is supposed to be inherited from Component
, then you might have some problems with your typings ( npm install @typings/react
). 或者,如果应该从
Component
继承state
,则您的键入可能会遇到一些问题( npm install @typings/react
)。
Use interfaces ( https://www.typescriptlang.org/docs/handbook/interfaces.html ): 使用界面 ( https://www.typescriptlang.org/docs/handbook/interfaces.html ):
interface Props = {
};
interface State = {
date: Date;
}
class Clock extends Component<Props, State> {
private timerId: any;
constructor(props: Props) {
super(props);
this.state = {
date: new Date()
};
}
...
}
You need to add correct generic arguments and you need to define the class properties. 您需要添加正确的泛型参数,并且需要定义类属性。 See comments.
看评论。
import * as React from 'react'; 从'react'导入*作为React;
interface IProps { }
interface IState {
date: Date;
}
class Clock extends React.Component<IProps, IState> { //You need to define both props and state
constructor(props: {}) {
super(props);
this.state = {
date: new Date()
};
}
timerId: any; //Props needs to be defined;
componentDidMount() {
this.timerId = setInterval(
() => this.tick(), 500
);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
const options = { hour24: false };
return (
<div className="clockDesign"> {this.state.date.toLocaleString('en-US', options)} </div>
);
}
}
export default Clock;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.