笔记react router 4(五)
2024-10-09 17:13:05
或许,你觉得我麻烦,明明一篇文章可以搞定的内容,非要写几篇。是不是正在吐槽我?没关系,我的目的达到了。手动傲娇( ̄∇ ̄)
然后,我们就要来聊一聊withRouter了。
我们都知道,当我在访问路由配置文件中的组件,通常我们称之为路由组件时,可以从他的props中访问到路由对象。如,location。但是,没有声明在路由中的组件,通常我们称之为非路由组件,比如路由组件中我们使用到的外部组件时,我们需要用到路由对象该怎么办呢?
在3.X中,我们要在非路由组件中使用history对象,需要手动引入history,就像这样,
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
或者,我们在路由组件中将获取到的路由对象手动传递给外部组件。
<Parent>
<Child routeProps = {this.props.location} />
</Parent>
再或者,我们可以使用H5的history API。
window.location
但是4.X中我们可以不用那么麻烦了,直接一个withRouter包裹你的外部组件,即可通过props访问到location, router及history等对象。
就像这样,
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router' class ShowTheLocation extends React.Component {
static propTypes = {
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>
)
}
} const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
来自:https://reacttraining.com/react-router/web/api/withRouter
接着再来看, component.WrappedComponent
// MyComponent.js
export default withRouter(MyComponent) // MyComponent.test.js
import MyComponent from './MyComponent'
render(<MyComponent.WrappedComponent location={{...}} ... />)
它用于创建一个包装组件上,通常用于测试。
wrappedComponnetRef这个函数的作用是refs获取组件实例。
class Container extends React.Component {
componentDidMount() {
this.component.doSomething()
} render() {
return (
<MyComponent wrappedComponentRef={c => this.component = c}/>
)
}
}
最新文章
- Bash 里的转义序列
- python无意中发现的
- 防止IFRAME页被嵌套
- eclipse @override错误
- 记录ASP.NET页面表单初始状态(主要是为了前台可以根据这个判断页面是否变动了)
- JDK8环境变量配置相关问题
- BZOJ 1037 [ZJOI2008]生日聚会Party(单调DP)
- Oracle初级优化sql
- Oracle创建表、修改字段类型
- 待解决ava.lang.OutOfMemoryError: PermGen space 	at java.lang.ClassLoader.defineClass1(Native Method)
- java中package指什么
- Linux let 命令
- ANDROID BINDER机制浅析
- POJ3273--Monthly Expense(Binary Search)
- 与IE的战斗
- VS2017仅我的代码警告
- 解决 openpyxl 垂直分页符和水平分页符同时添加的问题
- android(2)——Structure of an Android Application
- C++_函数4-函数重载与函数模板
- Python扫描指定文件夹下(包含子文件夹)的文件
热门文章
- .net 打包下载
- [0413] FFTSHIFT的四种写法
- data:image/png;base64 上传图像将图片转换成base64格式
- Tomcat的manager app管理web项目
- unity shader base pass and additional pass
- FreeCodeCamp---advanced Algorithm Scripting解法
- gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now
- python 操作剪切板
- Http请求处理流程 管道流程 MVC扩展HttpModule
- GridView实现拖拽排序以及数据交互