React路由器,来自子组件的访问历史对象



我想在一个深嵌套子组件中使用history.listen收听位置更改。

具有this.props.history的顶级母体组件是否会一直向下传递给子女组件?

我正在使用2.8.1 React-Router

如果我可以轻松地执行此操作,我愿意升级到较新的版本。

import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
  render() {
    // props also has match, location
    const { history } = this.props;
    ...
  }
}
export default withRouter(MyComponent);

您可以通过获取路由器上下文获得history

import React, {PropTypes} from 'react';
class myComponent extends React.Component {
   render() {
      console.log(this.context.history);
   }
}
myComponent.contextTypes = {
   history: PropTypes.object
}
export default myComponent;

最新更新