react router在ts中的宣告使用

2021-10-14 04:35:00 字數 1432 閱讀 7963

當我們使用react-router進行路由跳轉的時候,我們通常都會傳遞一些引數例如:param,state,query(目前已經被廢棄),但是結合typescript使用時,我們需要宣告元件的props型別,否則的話我們的tslint就會阻止程式的繼續執行,接下來我就介紹一下在react中元件的ts宣告:

class元件:

import react from 'react';

import from 'react-router';

// router中match.params的引數

inte***ce imatchparams

// router中staticcontext的引數

inte***ce istaticcontext extends staticcontext

// router中state的引數型別宣告

inte***ce istateparams

class olap extends react.component,iolapstate> = this.props;

}}

hooks元件:

import  from 'react-router';

import react, from 'react';

// router中match.params的引數

inte***ce imatchparams

// router中staticcontext的引數

inte***ce istaticcontext extends staticcontext

// router中state的引數型別宣告

inte***ce istateparams

inte***ce igraphanalysisprops extends routecomponentprops

const graphanalysis: fc= (props) => = props;

}

解釋:

首先我們的普通引數的props需要繼承react-router官方暴露的routecomponentprops介面,這個介面接收三個泛型:

第乙個泛型是router中的props.match下的params的引數,這個引數通常是指在路由路徑中配置的引數,例如:/user/:userid,此時userid就是對用的key,實際傳入路徑的值為對應的key值

第二個泛型是props.staticcontext的引數。我對這個引數並不了解,貌似是服務端渲染需要的引數。

第三個泛型是props.location.state的引數。這個引數在傳遞多個引數時使用。但是有個缺點是重新整理後會失效。解決辦法我之前的博文有提到。

希望對各位有所幫助。

聊聊React Router中的History

在學習react router時,看到有關history有如下描述 react router 是建立在 history 之上的。簡而言之,乙個 history 知道如何去監聽瀏覽器位址列的變化,並解析這個 url 轉化為 location 物件,然後 router 使用它匹配到路由,最後正確地渲染對...

ts定義陣列型別 ts中型別

1 vscode配置自動編譯 1.第一步 tsc inti 生成tsconfig.json 改 outdir js 2 第二步 任務 執行任務 監視tsconfig.json 2 typescript中的資料型別 typescript中為了使編寫的 更規範,更有利於維護,增加了型別校驗,在types...

TS中的介面

介面也是定義標準,他比抽象類更加全面 1.屬性介面function printlabel labelinfo void printlabel aaa 錯誤寫法 printlabel 傳入引數必須是以label為屬性名的物件對批量方法進行約束 可選屬性介面firstname?string 定義標準 i...