React中使用TypeScript

新建 react + typescript 項目:

npx create-react-app my-app --typescriptnode

已有項目遷移到typescript:

npm install --save typescript @types/node @types/react @types/react-dom @types/jestreact

TypeScript入門教程
git

1.引入插件

typescript中引入外部插件除了要引入插件自己還要引入它的聲明@types,@type統一管理第三方庫的聲明文件。
好比: 引入路由插件react-router-dom
npm i react-router-dom    還需    npm i @types/react-router-dom
github

查找聲明文件:microsoft.github.io/TypeSearch/typescript

2.ts中路由配置

前文我有說過react中的路由, 可是在ts環境裏你會發現引入@types/react-router-dom後直接使用withRouterts會一直報錯(ts2339), 緣由是必需使用 RuoteComponentProps,。npm

import React from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom';

type PropsType = RouteComponentProps & {};

class demo extends React.Component<PropsType, any> {
  
  constructor(props: PropsType) {
    super(props);
    this.state = {
      demo: 'demo',
    }
  }

  goBack() {
    this.props.history.goBack();
  }

  render() {
    return (
      <div>
        <button onClick={() => this.goBack()}>goBack</button>
      </div>
    )
  }
}

export default withRouter(demo);
複製代碼

3.props、state的使用

ts中React的組件中使用props或者state的時候,須要給組件傳兩個參數:指定類型(types)和對象的形(shape),緣由是ts的規則一切都應該按住預期的方式工做,類型檢查方面得先定義。bash

React.Compnent<types, shape>
複製代碼

若是類型對不上ts會提示報錯: react-router

應該對應類型: app

當你不肯定本身須要建立多少參數和參數類型時,建議使用any(任意類型):dom

class demo extends React.Component<any, any>
複製代碼

給組件傳入 RuoteComponentProps 後就至關於定義了 any , 若是是沒有使用路由插件的普通組型,須要注意若是React.Compnent<types, shape>中的types被定義了,則沒辦法接手來自路由的參數。

this.props.history.push({
  pathname: 'demo',
  state: {
    data: 1
  }
})
複製代碼
一樣的咱們能夠把 demoData 改成 any 來解決。

吐槽:React + TypeScript 一開始摸起來真的是很是多問題,由於第一次使用ts也是不少不習慣,加上還要適應react路由插件的聲明和各類特殊處理...

相關文章
相關標籤/搜索