在 React 中使用 Typescript


前言

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

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

主要步骤

  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、在typescript中使用antd等。

基本使用方法

  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 () }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM