withRouter是react-router的一個高階組件,可獲取history
render時會把match, location和history傳入props
react中經過路由渲染的組件才擁有路由參數,使用this.props.history.push('/a')跳轉到對應路由的頁面
使用withRouter可以將路由參數傳入this.props中
代碼舉例:
<code>import React, { Component } from 'react';
import { withRouter } from 'react-router';
@withRouter
export default class Header extends Component {
static displayName = 'Header';
static propTypes = {};
static defaultProps = {};
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
);
}
}
複製代碼/<code>
還有一種實現方法就是在要注入屬性的組件上使用'@withRouter'
代碼舉例:
<code>import React, { Component } from 'react';
import { withRouter } from 'react-router';
@withRouter
export default class Header extends Component {
static displayName = 'Header';
static propTypes = {};
static defaultProps = {};
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
);
}
}
複製代碼/<code>
使用@這種寫法的話,需要babel-plugin-transform-decorators-legacy包
執行:npm install babel-plugin-transform-decorators-legacy --save-dev
還需要在packag文件中的babel中配置,具體實現方式可以查看react @裝飾器相關文檔
<code>{
"plugins":[
"transform-decorators-legacy"
]
}/<code>
閱讀更多 IT暖男 的文章