新聞中心
一、基礎(chǔ)
俗話(huà)說(shuō)的好:“授人以魚(yú)不如授人以漁”,今天我也不知道自己的是“魚(yú)”還是“漁”,就講述一下自己這幾天學(xué)習(xí)React語(yǔ)法的忐忑之路。

定制開(kāi)發(fā)可以根據(jù)自己的需求進(jìn)行定制,成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)構(gòu)思過(guò)程中功能建設(shè)理應(yīng)排到主要部位公司成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)的運(yùn)用實(shí)際效果公司網(wǎng)站制作網(wǎng)站建立與制做的實(shí)際意義
看typescript中文文檔,然后總結(jié)了一波學(xué)習(xí)筆記。
總結(jié)完之后,發(fā)現(xiàn)ts里面有類(lèi)型推斷的能力,很多在React這樣的框架項(xiàng)目上根本用不上呀!!!
開(kāi)啟網(wǎng)上的瘋狂搜索功能,看看有沒(méi)有關(guān)于React這樣的文章,搜索了一下,確實(shí)有一些,講述有哪些React獨(dú)有的類(lèi)型;
臥槽,難道我為了用Ts又要記這些新的API嗎?這不是坑爹嗎?
“柳暗花明又一村”,偶然的機(jī)會(huì)我點(diǎn)擊了一個(gè)函數(shù)Reducer,神奇的發(fā)生了跳轉(zhuǎn),跳轉(zhuǎn)到index.d.ts;
這不就是聲明文件嗎?然后認(rèn)真分析Reducer;
type Reducer= (prevState: S, action: A) => S;
這不就是個(gè)函數(shù)的類(lèi)型別名嗎?其中兩個(gè)S和A分別是泛型,然后返回值是S,那如果這樣的話(huà),我根本就不用記住很多這個(gè)類(lèi)型了,當(dāng)需要的時(shí)候直接點(diǎn)擊該函數(shù),跳轉(zhuǎn)到對(duì)應(yīng)的聲明文件然后仔細(xì)研讀一波就好了,哈哈,貌似就是這么回事。
【自己試了試,確實(shí)可以解決80%的問(wèn)題】
不過(guò)為了提高開(kāi)發(fā)效率,節(jié)省自己研究的成本,我還是寫(xiě)出幾個(gè)常用的React中的ts語(yǔ)法,方便開(kāi)發(fā)的時(shí)候套用。
二、 React中內(nèi)置函數(shù)
React中內(nèi)置函數(shù)由很多,我們就挑幾個(gè)常用的來(lái)學(xué)習(xí)一下。
2.1 React.FC< P >
React.FC<>是函數(shù)式組件在TypeScript使用的一個(gè)泛型,F(xiàn)C就是FunctionComponent的縮寫(xiě),事實(shí)上React.FC可以寫(xiě)成React.FunctionComponent。
import React from 'react';
interface demo1PropsInterface {
attr1: string,
attr2 ?: string,
attr3 ?: 'w' | 'ww' | 'ww'
};
// 函數(shù)組件,其也是類(lèi)型別名
// type FC= FunctionComponent
;
// FunctionComponent是一個(gè)接口,里面包含其函數(shù)定義和對(duì)應(yīng)返回的屬性
// interface FunctionComponent{
// // 接口可以表示函數(shù)類(lèi)型,通過(guò)給接口定義一個(gè)調(diào)用簽名實(shí)現(xiàn)
// (props: PropsWithChildren, context?: any): ReactElement
| null;
// propTypes?: WeakValidationMap| undefined;
// contextTypes?: ValidationMap| undefined;
// defaultProps?: Partial| undefined;
// displayName?: string | undefined;
// }
const Demo1: React.FC= ({
attr1,
attr2,
attr3
}) => {
return (
hello demo1 {attr1}
);
};
export default Demo1;
2.2 React.Component< P, S >
React.Component< P, S > 是定義class組件的一個(gè)泛型,第一個(gè)參數(shù)是props、第二個(gè)參數(shù)是state。
import React from "react";
// props的接口
interface demo2PropsInterface {
props1: string
};
// state的接口
interface demo2StateInterface {
state1: string
};
class Demo2 extends React.Component{
constructor(props: demo2PropsInterface) {
super(props);
this.state = {
state1: 'state1'
}
}
render() {
return (
{this.state.state1 + this.props.props1}
);
}
}
export default Demo2;
2.3 React.createContext、useContext、和useReducer中Ts使用
這三者經(jīng)常一起使用,用來(lái)進(jìn)行跨級(jí)組件間的數(shù)據(jù)傳輸,ts版如下所示:
- React.createContext
其會(huì)創(chuàng)建一個(gè)Context對(duì)象,當(dāng)React渲染一個(gè)訂閱了這個(gè)Context對(duì)象的組件,這個(gè)組件會(huì)從組件樹(shù)中離自身最近的那個(gè)匹配的Provider中讀取到當(dāng)前的context值。【注:只要當(dāng)組件所處的樹(shù)沒(méi)有匹配到Provider時(shí),其defaultValue參數(shù)參會(huì)生效】
const MyContext = React.createContext(defaultValue);
const Demo = () => {
return (
// 注:每個(gè)Context對(duì)象都會(huì)返回一個(gè)Provider React組件,它允許消費(fèi)組件訂閱context的變化。
// ……
);
}
- useContext
接收一個(gè) context 對(duì)象(React.createContext 的返回值)并返回該 context 的當(dāng)前值。當(dāng)前的 context 值由上層組件中距離當(dāng)前組件最近的 的 value prop 決定。語(yǔ)法如下所示:「const value = useContext(MyContext);」
import React, {useContext} from "react";
const MyContext = React.createContext('');
const Demo3Child: React.FC<{}> = () => {
const context = useContext(MyContext);
return (
{context}
);
}
const Demo3: React.FC<{}> = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
);
};
- useReducer
useState的替代方案,接收一個(gè)形如(state, action) => newState的reducer,并返回當(dāng)前state以及其配套的dispatch方法。語(yǔ)法如下所示:「const [state, dispatch] = useReducer(reducer, initialArg, init);」
import React, {useReducer, useContext} from "react";
interface stateInterface {
count: number
};
interface actionInterface {
type: string,
data: {
[propName: string]: any
}
};
const initialState = {
count: 0
};
// React.Reducer其實(shí)是類(lèi)型別名,其實(shí)質(zhì)上是type Reducer = (prevState: S, action: A) => S;
// 因?yàn)閞educer是一個(gè)函數(shù),其接受兩個(gè)泛型參數(shù)S和A,返回S類(lèi)型
const reducer: React.Reducer = (state, action) => {
const {type, data} = action;
switch (type) {
case 'increment': {
return {
...state,
count: state.count + data.count
};
}
case 'decrement': {
return {
...state,
count: state.count - data.count
};
}
default: {
return state;
}
}
}
// React.createContext返回的是一個(gè)對(duì)象,對(duì)象接口用接口表示
// 傳入的為泛型參數(shù),作為整個(gè)接口的一個(gè)參數(shù)
// interface Context {
// Provider: Provider;
// Consumer: Consumer;
// displayName?: string | undefined;
// }
const MyContext: React.Context<{
state: stateInterface,
dispatch ?: React.Dispatch
}> = React.createContext({
state: initialState
});
const Demo3Child: React.FC<{}> = () => {
const {state, dispatch} = useContext(MyContext);
const handleClick = () => {
if (dispatch) {
dispatch({
type: 'increment',
data: {
count: 10
}
})
}
};
return (
{state.count}
);
}
const Demo3: React.FC<{}> = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
);
};
export default Demo3;
三、React中事件處理函數(shù)
React中的事件是我們?cè)诰幋a中經(jīng)常用的,例如onClick、onChange、onMouseMove等,那么應(yīng)該如何用呢?
3.1 不帶event參數(shù)
當(dāng)對(duì)應(yīng)的事件處理函數(shù)不帶event參數(shù)時(shí),這個(gè)時(shí)候用起來(lái)很簡(jiǎn)單,如下所示:
const Test: React.FC<{}> = () => {
const handleClick = () => {
// 做一系列處理
};
return (
);
};
3.2 帶event參數(shù)
老鐵們可以試試,當(dāng)事件處理函數(shù)待event參數(shù)的時(shí)候,如果不做任何處理,鐵定報(bào)錯(cuò),此時(shí)就按照第一節(jié)的方法論來(lái)試一試:
- 帶上event參數(shù),報(bào)錯(cuò);
const Test: React.FC<{}> = () => {
// 報(bào)錯(cuò)了,注意不要這么寫(xiě)……
const handleClick = event => {
// 做一系列處理
event.preventDefault();
};
return (
);
};
- 點(diǎn)擊onClick參數(shù),跳轉(zhuǎn)到index.d.ts文件;
// onClick是MouseEventHandler類(lèi)型
onClick?: MouseEventHandler| undefined;
// 那MouseEventHandler又是啥?原來(lái)是個(gè)類(lèi)型別名,泛型是Element類(lèi)型
type MouseEventHandler= EventHandler >;
// 那么泛型Element又是什么呢?其是一個(gè)接口,通過(guò)繼承該接口實(shí)現(xiàn)了很多其它接口
interface Element { }
interface HTMLElement extends Element { }
interface HTMLButtonElement extends HTMLElement { }
interface HTMLInputElement extends HTMLElement { }
// ……
- 至此,就知道該位置應(yīng)該怎么實(shí)現(xiàn)了;
const Test: React.FC<{}> = () => {
const handleClick: React.MouseEventHandler = event => {
// 做一系列處理
event.preventDefault();
};
return (
);
}; 對(duì)于其它的事件一樣,按照上述三個(gè)步驟,就可以一篇搞定,不需要進(jìn)行所謂的死記硬背。
四、普通函數(shù)
普通函數(shù)是通用的,但是還是在這個(gè)位置提一下。
- 一個(gè)具體類(lèi)型的輸入輸出函數(shù);
// 參數(shù)輸入為number類(lèi)型,通過(guò)類(lèi)型判斷直接知道輸出也為number
function testFun1 (count: number) {
return count * 2;
}
- 一個(gè)不確定類(lèi)型的輸入、輸出函數(shù),但是輸入、輸出函數(shù)類(lèi)型一致;
// 用泛型
function testFun2(arg: T): T {
return arg;
}
- async函數(shù),返回的為Promise對(duì)象,可以使用then方法添加回調(diào)函數(shù),Promise是一個(gè)泛型函數(shù),T泛型變量用于確定then方法時(shí)接收的第一個(gè)回調(diào)函數(shù)的參數(shù)類(lèi)型。
// 用接口
interface PResponse{
result: T,
status: string
};
// 除了用接口外,還可以用對(duì)象
// type PResponse= {
// result: T,
// status: string
// };
async function testFun3(): Promise> {
return {
status: 'success',
result: 10
}
}
當(dāng)前標(biāo)題:React+Ts,這樣學(xué)起來(lái)確實(shí)簡(jiǎn)單?。。?
本文URL:http://fisionsoft.com.cn/article/cddgcie.html


咨詢(xún)
建站咨詢(xún)
