使用 TypeScript
編寫 React
需要注意的規(guī)范
必須遵守的要求:
- 所有用到
jsx
語法的文件都需要以tsx
后綴命名 - 使用組件聲明時(shí)的
Component<P, S>
泛型參數(shù)聲明终议,來代替PropTypes
進(jìn)行類型校驗(yàn)
額外的代碼規(guī)范:
- 全局變量或者自定義的
window
對(duì)象屬性汇竭,統(tǒng)一在項(xiàng)目根下的global.d.ts
中進(jìn)行聲明定義 - 對(duì)于項(xiàng)目中常用到的接口數(shù)據(jù)對(duì)象,最好在
types/
目錄下定義好其結(jié)構(gòu)化類型聲明
創(chuàng)建項(xiàng)目
npx create-react-app typescript-react-app --scripts-version=react-scripts-ts
react-scripts-ts是一系列適配器穴张,它利用標(biāo)準(zhǔn)的create-react-app工程管道并把TypeScript混入進(jìn)來细燎。
項(xiàng)目創(chuàng)建成功后,此時(shí)項(xiàng)目結(jié)構(gòu)如下所示:
typescript-react-app/
├─ node_modules/
├─ public/
├─ src/
│ └─ ...
├─ .gitignore
├─ images.d.ts
├─ package.json
├─ README.md
├─ tsconfig.json
├─ tsconfig.prod.json
├─ tsconfig.test.json
├─ tslint.json
└─ yarn.lock
注意:
- tsconfig.json包含了工程里TypeScript特定的選項(xiàng)皂甘。
- tslint.json保存了要使用的代碼檢查器的設(shè)置玻驻,TSLint。
- package.json包含了依賴偿枕,還有一些命令的快捷方式璧瞬,如測(cè)試命令,預(yù)覽命令和發(fā)布應(yīng)用的命令渐夸。
- public包含了靜態(tài)資源如HTML頁面或圖片嗤锉。除了index.html文件外,其它的文件都可以刪除墓塌。
- src包含了TypeScript和CSS源碼档冬。index.tsx是強(qiáng)制使用的入口文件。
運(yùn)行項(xiàng)目
先運(yùn)行項(xiàng)目桃纯,看看是否能夠正常啟動(dòng),如果可以披坏,說明項(xiàng)目創(chuàng)建沒有問題态坦。 運(yùn)行命令:
$ npm run start
# 或者運(yùn)行 yarn run start
React 配合 TypeScript 的基本使用
在當(dāng)前項(xiàng)目中,可以看到 index.tsx 和 App.jsx 文件中已經(jīng)使用了 TypeScript棒拂,我們現(xiàn)在自己來用 TypeScript 編寫一個(gè) React 組件吧伞梯。
定義一個(gè) Counter 組件
我們?cè)?src 下創(chuàng)建一個(gè) container目錄,新增 Counter 組件:
Counter.tsx
import * as React from 'react';
// 創(chuàng)建類型接口
export interface Iprops {
value: number
}
// 使用接口代替 PropTypes 進(jìn)行類型校驗(yàn):函數(shù)組件
const Counter = ({ value }: Iprops) => {
return <p>Clicked: { value } times</p>
}
// 使用接口代替 PropTypes 進(jìn)行類型校驗(yàn):使用類的方式
const Counter = ({ value }: Iprops) => {
return <p>Clicked: { value } times</p>
}
export default Counter;
我們可以使用函數(shù)組件或者類組件帚屉,注意兩者的區(qū)別是類方式組件有react的生命周期谜诫,而函數(shù)組件沒有,建議函數(shù)組件來做純顯示
在 App.tsx 中引用 Counter 組件并展示
import * as React from 'react';
import './App.css';
import Counter from './components/Counter.jsx';
// import logo from './logo.svg';
class App extends React.Component {
public render() {
return (
<div className="App">
<Counter value={ 0 } />
</div>
);
}
}
export default App;
運(yùn)行項(xiàng)目:npm run start
攻旦,可以看到瀏覽器中展示出了 Clicked: 0 times
喻旷,說明我們第一個(gè) Counter 組件已經(jīng)編寫并使用成功了。
進(jìn)階:配合 Redux 進(jìn)行使用
安裝項(xiàng)目需要的插件
安裝redux和react-redux以及它們的類型文件做為依賴牢屋。
$ npm install -S redux react-redux @types/react-redux
這里我們不需要安裝@types/redux且预,因?yàn)镽edux已經(jīng)自帶了聲明文件(.d.ts文件)槽袄。
定義應(yīng)用的狀態(tài) State
一般會(huì)將常用的結(jié)構(gòu)類型存放到 /types 目錄下。所以我們?cè)?src 目錄下新建 types 目錄锋谐。此時(shí)項(xiàng)目中只有一個(gè) state遍尺,就是 Counter 中的點(diǎn)擊次數(shù),所以就沒有使用借口來作為約束涮拗,而是直接使用了 type乾戏。
type/index.ts
// 定義 State 結(jié)構(gòu)類型
export type StoreState = number;
添加 actions-type
在 src 下創(chuàng)建 store目錄,在const.ts 文件中添加需要響應(yīng)的消息類型
src/store/const.ts
// 定義增加 state 類型常量
export const INCREMENT = "INCREMENT";
export type INCREMENT_TYPE = typeof INCREMENT;
// 定義減少 state 類型常量
export const DECREMENT = "DECREMENT";
export type DECREMENT_TYPE = typeof DECREMENT;
這里的const/type模式允許我們以容易訪問和重構(gòu)的方式使用TypeScript的字符串字面量類型三热。 接下來鼓择,我們創(chuàng)建一些 actions 以及創(chuàng)建這些 actions 的函數(shù)
添加 actions
src/store/actions/index.ts
import {DECREMENT, DECREMENT_TYPE, INCREMENT, INCREMENT_TYPE} from '../const'
export interface IINCREMENTAction {
type: INCREMENT_TYPE;
}
export interface IDECREMENTAction {
type: DECREMENT_TYPE;
}
// 定義 modifyAction 類型,包含 IINCREMENTAction 和 IDECREMENTAction 接口類型
export type ModifyAction = IINCREMENTAction | IDECREMENTAction;
// 增加 state 次數(shù)的方法
export const increment = (): IINCREMENTAction => ({
type: INCREMENT,
})
// 減少 state 次數(shù)的方法
export const decrement = (): IDECREMENTAction => ({
type: DECREMENT
})
添加 reducer
我們的reducer將放在src/reducers/index.tsx文件里康铭。 它的功能是保證增加操作會(huì)讓 times
加1惯退,減少操作則要將 times
減1。
reducers/index.tsx
import { ModifyAction } from '../actions';
import { DECREMENT, INCREMENT } from '../const';
// 處理并返回 state
export default (state = 0, action: ModifyAction): number => {
switch (action.type) {
case INCREMENT:
return state + 1
case DECREMENT:
return state - 1
default:
return state
}
}
注意上面整個(gè)reducer只有一個(gè)reducer
从藤,就是一個(gè)number
催跪,如果需要多個(gè)reducer可以combineReducers組建多個(gè)reducer
import { combineReducers } from 'redux'
// 一個(gè)state
function count (state = 0, action: ModifyAction): number => {
switch (action.type) {
case INCREMENT:
return state + 1
case DECREMENT:
return state - 1
default:
return state
}
function test (state = 0, action: ModifyAction): number => {
switch (action.type) {
...
default:
return state
}
這樣可以吧store變成一個(gè)對(duì)象來組合reducer = state
const rootReducer = combineReducers({
count,
test
})
創(chuàng)建容器組件
創(chuàng)建一個(gè) container
目錄,用來存放需要與數(shù)據(jù)交互的組件夷野,新建 CounterCon.tsx
文件.
兩個(gè)關(guān)鍵點(diǎn)是初始的 Counter
組件和 react-redux
的 connect
函數(shù)懊蒸。 connect
可以將我們的 Counter
組件轉(zhuǎn)換成一個(gè)容器,通過以下兩個(gè)函數(shù):
- mapStateToProps將當(dāng)前store里的數(shù)據(jù)以我們的組件需要的形式傳遞到組件悯搔。
- mapDispatchToProps利用dispatch函數(shù)骑丸,創(chuàng)建回調(diào)props將actions送到store。
import * as React from 'react';
import { connect } from 'react-redux';
import { Dispatch } from 'redux';
import { decrement, increment } from '../store/actions';
import { StoreState } from '../types';
// 創(chuàng)建類型接口
export interface IProps {
value: number,
onIncrement: () => void,
onDecrement: () => void
}
// 使用接口代替 PropTypes 進(jìn)行類型校驗(yàn)
class Counter extends React.PureComponent<IProps> {
public componentWillMount () {
// tslint:disable-next-line
console.log(this.props) // 這里的prop是拿不到dispatch函數(shù)妒貌,因?yàn)榻M合高階函數(shù)的時(shí)候做了處理通危,沒有傳入dispatch,只有{value: 0, onDecrement: ?, onIncrement: ?}
}
public render() {
const { value, onIncrement, onDecrement } = this.props;
return (
<p>
Clicked: { value } times
<br />
<br />
<button onClick={ onIncrement } style={{ marginRight: 20 }}> + </button>
<button onClick={ onDecrement }> - </button>
</p>
)
}
}
// 將 reducer 中的狀態(tài)插入到組件的 props 中
// 下面是單個(gè)reducer的時(shí)候灌曙,多個(gè)的時(shí)候需要選傳入哪個(gè)reducer
// const { test, count } = state
const mapStateToProps = (state: StoreState): { value: number } => ({
value: state
})
// 將 對(duì)應(yīng)action 插入到組件的 props 中
const mapDispatchToProps = (dispatch: Dispatch) => ({
onDecrement: () => dispatch(decrement()),
onIncrement: () => dispatch(increment())
})
// 使用 connect 高階組件對(duì) Counter 進(jìn)行包裹
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
另外如果connect的時(shí)候不傳入數(shù)據(jù)的時(shí)候connect()(Test)
菊碟,組件的this.prop
只能拿到dispatch的函數(shù),和外層父元素的props
在刺,并不能拿到store
的數(shù)據(jù)逆害,而且高階函數(shù)返回一個(gè)可以注入store的prop的組件,依然可以接受外層的props
蚣驼,所以注意reducer
必須要注入魄幕,否則沒有,只有dispatch
,而且必須是一個(gè)對(duì)象!!!!!!
創(chuàng)建 store
讓我們回到src/index.tsx。 要把所有的東西合到一起颖杏,我們需要?jiǎng)?chuàng)建一個(gè)帶初始狀態(tài)的store纯陨,并用我們所有的reducers來設(shè)置它。 并且使用 react-redux 的 Provider 將 props 和 容器連接起來
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import App from './App';
import './index.css';
import reducer from './reducer';
import registerServiceWorker from './registerServiceWorker';
// 1、創(chuàng)建 store
const store = createStore(reducer, composeWithDevTools());
ReactDOM.render(
// 2队丝、然后使用react-redux的Provider將props與容器連通起來
<Provider store={ store }>
<App />
</Provider> ,
document.getElementById('root') as HTMLElement
);
registerServiceWorker();
其中composeWithDevTools
是Chrome里面的調(diào)試工具
回到我們的 App.tsx 文件中靡馁。改寫如下:
App.tsx
import * as React from 'react';
import './App.css';
import Counter from './containers/Counter'
import logo from './logo.svg';
class App extends React.Component {
public render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<Counter/>
</div>
);
}
}
export default App;
注意,此時(shí) Counter
不再需要 props
了机久,因?yàn)槲覀兪褂昧?connect
函數(shù)為包裹起來的 Hello
組件的 props
適配了應(yīng)用的狀態(tài)臭墨,當(dāng)然也可以傳進(jìn)去,props也可以拿到的膘盖。
此時(shí)胧弛,運(yùn)行項(xiàng)目,點(diǎn)擊 + 或者 - 按鈕侠畔,即可看到 times
的次數(shù)會(huì)發(fā)生變化结缚。
總結(jié)
至此,對(duì)于使用 TypeScript
編寫 React
應(yīng)用應(yīng)該有了一定的了解软棺。其實(shí)寫法也比較固定红竭,剛接觸的話可能有些地方容易出現(xiàn)問題,多寫幾個(gè)組件之后喘落,應(yīng)該就沒什么問題了茵宪。在編寫項(xiàng)目的過程中,create-react-app
自帶的 tslint
可能要求比較嚴(yán)嚴(yán)格瘦棋,比如:
- 在標(biāo)簽里不允許使用 lambda 表達(dá)式稀火,在
tslint.json
文件rules
屬性中添加:"jsx-no-lambda": false
即可 - 在導(dǎo)入模塊時(shí),必須按照字母順序?qū)攵呐螅?
tslint.json
文件rules
屬性中添加:"ordered-imports": false
即可
還有很多別的配置凰狞,有需要的話,可以查看文檔:TSLint core rules沛慢。
參考文檔
[使用 TypeScript + React + Redux 進(jìn)行項(xiàng)目開發(fā)(入門篇赡若,附源碼]