withRouter的用法-实现react子组件的路由跳转

需要实现这样一个需求:点击子组件的某个图标实现路由的跳转。一开始我是直接使用react-router的语法的,然后发现不可以实现页面的完全跳转,需要to的组件被包裹在子组件内部了。。。。搜了一下发现需要用到withRouter。

withRouter的作用是,当我们需要一个不是router但却能实现跳转,比如说点击logo图片,跳转到首页之类的。withRouter将组件包裹到router中, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中。

下面分别展示withRouter和react-router的写法,毕竟我写都写了。

首先都要在顶层进行路由注册

1
2
3
4
5
6
<Router>
<Switch>
<Route exact path="/" > <Card /></Route>
<Route path="/cart" ><Cart /></Route>
</Switch>
</Router>

withRouter的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//引入withRouter
import { withRouter } from 'react-router-dom';
class Cards extends Component {
toCart = () => {
//跳转到cart路由
this.props.history.push('/cart');
}
render() {
return (
<div className='card'>
<img className='add' src={add} alt="addPic" onClick={this.toCart.bind(this)}></img>
{/* <Router>
<Link className='add' to="/cart">
</Link>
<Route path="/cart" component={Cart} />
</Router> */}
</div>
)
}
}
export default withRouter(Cards);

点击图片触发onClick里面的toCart方法,然后因为withRouter将history对象放在了Cards组件中了,所以toCart方法直接将cart push进路由就行了,最后用withRouter包裹导出。

如果withRouter和connect一起用一定把withRouter写外面。

1
export default   withRouter(connect(({ menu, mapindex }) => ({ menu, mapindex }))(TopMenu));

react-router的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Cart from './cart'
class Cards extends Component {
render() {
return (
<div className='card'>
<Router>
<Link to="/cart">
<img className='add' src={add} alt="addPic"></img>
</Link>
<Route path="/cart" component={Cart} />
</Router>
</div>
)
}
}
export default Cards

其实从语法上就可以看出,route标签中加载了Cart组件,应该是嵌套路由

查看评论