React - 一般组件 withRouter 的使用(让一般组件具备路由组件特有的API属性)
一. withRouter 理解
withRouter
可以加工一般组件,让一般组件具备路由组件特有的 API 属性,会将history
,location
, match
属性放到这个组件的props
属性中。withRouter
的返回值是一个新组件。
二. withRouter 使用
import React, { Component } from "react";
import { withRouter } from "react-router-dom";
class Header extends Component {
back = () => {
this.props.history.goBack();
};
forward = () => {
this.props.history.goForward();
};
go = (num) => {
this.props.history.go(num);
};
render() {
console.log(123,this.props);
return (
<div className="page-header">
<h2>导航栏</h2>
<button onClick={this.back}>回退</button>
<button onClick={this.forward}>前进</button>
<button onClick={() => this.go(2)}>前进2步</button>
<button onClick={() => this.go(-2)}>后退2步</button>
</div>
);
}
}
export default withRouter(Header);