前言
用 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等。
電腦刺綉綉花廠 http://www.szhdn.com 廣州品牌設計公司https://www.houdianzi.com
基本使用方法
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 () }