注意: 默认情况下,只有路由<Router>直接渲染的组件才能够获取到路由信息(比如:history.go()等)
如果需要在其他组件中获取到路由信息可以通过withRouter高阶组件来获取
1.从react - router - dom中导入withRouter高阶组件
import { withRouter } from "react-router-dom"
2.使用withRouter高阶组件包装NavHeader组件 目的:包装后,就可以在组件中获取到当前路由信息了
//withRouter(NavHeader)函数的返回值也是一个组件
export default withRouter(NavHeader)
3.从props中解构出history对象
4.调用history.go()方法
5.从props中解构出onLeftClick函数,实现自定义返回按钮的点击事件
完整例子:
import React from "react"
import { NavBar, Icon } from "antd-mobile"
import { withRouter } from "react-router-dom"
// 注意: 默认情况下,只有路由Router直接渲染的组件才能够获取到路由信息(比如:history.go()等)
// 如果需要在其他组件中获取到路由信息可以通过withRouter高阶组件来获取
// 1.从react - router - dom中导入withRouter高阶组件
// 2.使用withRouter高阶组件包装NavHeader组件 目的:包装后,就可以在组件中获取到当前路由信息了
// 3.从props中解构出history对象
// 4.调用history.go()方法
// 5.从props中解构出onLeftClick函数,实现自定义返回按钮的点击事件
function NavHeader({ children, history, onLeftClick }) {
//默认点击行为
const defaultHandler = () => history.go(-1)
return <NavBar
mode="light"
icon={<Icon type="left" />}
onLeftClick={onLeftClick || defaultHandler}
className="navbar"
>{children}</NavBar>
}
//withRouter(NavHeader)函数的返回值也是一个组件
export default withRouter(NavHeader)