目录
见:如何在React项目中引入TypeScript?_duansamve的博客-CSDN博客
其基本使用和javascript编写React项目时差不多
这是一份.tsx文件代码:可以看到和之前的.jsx使用并无太大差别
- import React, { Component } from "react";
-
- class Hello extends Component {
- render () {
- return (
- <div>
- <h1>Helloh1>
- div>
- );
- }
- }
-
- export default Hello;
- import React, { Component } from "react";
-
- interface IProps{
- name: string,
- age: number,
- work?:string
- }
-
- class Hello extends Component <IProps>{
-
- public constructor (props: any, context: any) {
- super(props, context);
- }
-
- public render () {
- const {name,age,work}=this.props
- return (
- <div>
- <h1>Hello:{name}h1>
- <h2>{age}h2>
- <h3>{work}h3>
- div>
- );
- }
- }
-
- export default Hello;
注意:使用.tsx时需要明确传入变量的类型,正确的写法应如上所示。any表示传入的可以是任何类型,TypeScript增加了类型限制和类的公开性关键字。TypeScript每次编译都会检查类型是否正确。

state默认是只读的,所以使用时可以有以下两种方式
- import React, { Component } from "react";
-
- //通过接口声明状态
- interface IState {
- count: number
- }
-
- class Hello extends Component
IState> { -
-
- // constructor (props: any, context: any) {
- // super(props, context);
- // this.state={
- // count: 1000
- // }
- // }
-
- // 实现state
- public readonly state: Readonly<IState> = {
- count: 1
- };
-
- clickHandler=()=>{
- this.setState({
- count: this.state.count + 1
- });
- };
-
- public render () {
- return (
- <div>
- <h1>Hello.count:{this.state.count}h1>
- <button onClick={this.clickHandler}>clickbutton>
- div>
- );
- }
- }
-
- export default Hello;

TypeScript和Javascript的区别在于加入对类型的限制,有点类似于强类型的语言,实质是为了更好的管理维护代码。