我有代码
路由器.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"));
历史.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)?
在反应路由器 1.0.3 我这样做了: this.props.children.props.route.component_id
感谢您的关注!
React v16.8+ 和 React Router v5+ 的更新:
使用useLocation
钩子。
import { useLocation } from 'react-router-dom';
const Main = ({ children }) => {
const location = useLocation();
console.log(location.pathname); // outputs currently active route
return children;
};
export default Main;
用 包裹您的组件,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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句