React Router 4.获取活动路由

时间:2018-01-11 15:35:32

标签: javascript reactjs react-router

我有代码

router.js

import React from 'react';
import {render} from "react-dom";
import history from './history';
import {Router, Route} from 'react-router'

import Main from "./main/component";
import Profile from "./profile/component";
import TextStatus from "./textstatus/component";
import ContactList from "./contactlist/component";

render((
  <Router history={history}>
    <Main>
      <Route
        path="/:user_name"
        component={Profile}
        component_id="Profile"
      />
      <Route
        path="/:user_name/status"
        component={TextStatus}
        component_id="TextStatus"
      />
      <Route
        path="/:user_name/contacts"
        component={ContactList}
        component_id="ContactList"
      />
    </Main>
  </Router>

), document.getElementById("main"));

history.js

import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory();
export default history;

main / component.js //主要布局

import React from 'react';
class Main extends React.Component {
   render() {
      return (this.props.children)
   }
}

如何在Main组件中获取当前路由(component_id)?

在react router 1.0.3中,我这样做了:this.props.children.props.route.component_id

感谢您的关注!

2 个答案:

答案 0 :(得分:1)

您可以使用withRouter HOC按顺序包装主要组件,以从上下文中获取位置道具。

答案 1 :(得分:1)

使用withRouter打包您的组件,然后您可以使用this.props.location.pathname访问当前有效路线。

例如:

import React from 'react';
class Main extends React.Component {
   render() {
      console.log(this.props.location.pathname); // outputs currently active route
      return (this.props.children)
   }
}
export default withRouter(Main);