You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
通过 withRouter 高阶组件可以访问 history 对象的属性,以及最近的匹配项。每次渲染组件时(renders)时,withRouter都会将更新的匹配(match)、位置(location) 和 history props传递给包装组件(wrapped component)。
importReactfrom"react";importPropTypesfrom"prop-types";import{withRouter}from"react-router";// 显示当前路径名classShowTheLocationextendsReact.Component{staticpropTypes={match: PropTypes.object.isRequired,location: PropTypes.object.isRequired,history: PropTypes.object.isRequired};render(){const{ match, location, history }=this.props;return<div>You are now at {location.pathname}</div>;}}// Create a new component that is "connected" (to borrow redux terminology) to the router.//创建一个 “连接(connected)” 到路由器的新组件(借用redux术语)。constShowTheLocationWithRouter=withRouter(ShowTheLocation);
API
withRouter
在 react 中只有经过路由渲染的组件才拥有路由参数,例如:使用this.props.history.push('/a')跳转到对应路由的页面。而withRouter作用就是将路由参数传入this.props中,这样一来那些没有使用路由跳转的组件,也能够获取路由参数了。
withRouter组件有两种使用方法:(1)withRouter(App) (2)直接在组件上使用'@withRouter'。
使用@这种写法的话,需要babel-plugin-transform-decorators-legacy包。
还需要在packag文件中的babel中配置,具体实现方式可以查看react @装饰器相关文档。
通过 withRouter 高阶组件可以访问 history 对象的属性,以及最近的匹配项。每次渲染组件时(renders)时,withRouter都会将更新的匹配(match)、位置(location) 和 history props传递给包装组件(wrapped component)。
重点:
静态方法与属性
包装组件所有不是 react 的(no-react)特定的静态方法和属性自动复制到“已连接”组件。
Component.WrappedComponent
包装的组件在返回的组件上作为静态属性 WrappedComponent 公开,它可以用于隔离测试组件等。
wrappedComponentRef: func
该函数将作为ref prop传递给包装的组件。
The text was updated successfully, but these errors were encountered: