我有代码
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
感谢您的关注!
答案 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);