用word做旅游網(wǎng)站新聞危機公關(guān)
一 基本介紹
作用: 把不是通過路由切換過來的組件中,將react-router 的 history、location、match 三個對象傳入props對象上。比如首頁!
默認情況下必須是經(jīng)過路由匹配渲染的組件才存在this.props,才擁有路由參數(shù),才能使用編程式導(dǎo)航的寫法,執(zhí)行this.props.history.push(‘/detail’)跳轉(zhuǎn)到對應(yīng)路由的頁面
然而不是所有組件都直接與路由相連(通過路由跳轉(zhuǎn)到此組件)的,當這些組件需要路由參數(shù)時,使用withRouter就可以給此組件傳入路由參數(shù),此時就可以使用this.props
二 withRouter使用
import React from 'react';
import {withRouter} from '../react-router-dom';
class NavHeader extends React.Component{render(){return <div onClick={()=>this.props.history.push('/')}>{this.props.title}</div>}
}export default withRouter(NavHeader);
三 withRouter源碼實現(xiàn)
import React from 'react';
import RouterContext from './RouterContext';
function withRouter(OldComponent){return props=>(<RouterContext.Consumer>{(value)=>(<OldComponent {...value} {...props}/>)}</RouterContext.Consumer>)
}
export default withRouter;