当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 在 React 中使用 Typescript

在 React 中使用 Typescript

2020年01月18日  | 移动技术网IT编程  | 我要评论

前言

  用 typescript 写 react 可比写 vue 舒服太多了,react 对 ts 的支持可谓天生搭档,如果要用 ts 重构项目,不像 vue 对项目破坏性极大,react 可以相对轻松的实现重构。

顺便一提:全局安装的 create-react-app 现已无法再下载完整的 react 项目模版必须先 npm uninstall -g create-react-app 移除命令 再 npx create-react-app demo 下载模版,参考

主要步骤

  1. 生成一个全新的 ts + react 的模版 可直接使用指令:npx create-react-app demo --typescript,注意在未来的版本中该指令会被替换为 npx create-react-app demo --template typescript,该模版包含了全套正常运行 react 所需的包和配置,无需再额外手动安装 typescript 等,其中还包含了自动化测试文件以及pwa所需文件等,可自行根据需求增删。

如在已有项目中使用typescript,需要手动安装 typescript @types/react @types/react-dom(使用@types/前缀表示我们额外要获取react和react-dom的声明文件),然后在根目录下创建一个 tsconfig.json 文件,改后缀为 .tsx

{
  "compileroptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowjs": true,
    "skiplibcheck": true,
    "esmoduleinterop": true,
    "allowsyntheticdefaultimports": true,
    "strict": true,
    "forceconsistentcasinginfilenames": true,
    "module": "esnext",
    "moduleresolution": "node",
    "resolvejsonmodule": true,
    "isolatedmodules": true,
    "noemit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

  2. 使用各种第三方库,如路由库 react-router-dom(需要额外安装声明文件@types/react-router-dom)、状态管理库 react-redux(需要额外安装声明文件@types/react-redux)、axios、等。

基本使用方法

  1. 类组件写法

import react from 'react'

interface props {
    enddate: string,
    timeout: any
}
interface state {
    now: any
}
let timer: any = null
class countdown extends react.component<props, state>{
    readonly state: readonly<state> = {
        now: moment()
    }

    componentdidmount(){
        timer = setinterval((): void => {
            this.setstate({
                now: moment()
            })
        }, 1000)
    }
    componentwillunmount(){
        clearinterval(timer)
    }
    
    get countdown(){ //类似 vue 中的计算属性
        return (enddate: string): string => {
            //...
            }
        }
    }

    render(): any{
        return (
            ......
        )
    }
}

export default countdown

  2. 函数组件写法

const app: react.fc<prop> = (prop) => {
    return ()
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网