gpt4 book ai didi

javascript - React Router 4. 获取事件路由

转载 作者:行者123 更新时间:2023-11-28 13:03:47 24 4
gpt4 key购买 nike

我有代码

路由器.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)
}
}

如何获取主组件中的当前路由(component_id)?

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

感谢您的关注!

最佳答案

React v16.8+ 和 React Router v5+ 更新:

使用useLocation钩子(Hook)。

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);

关于javascript - React Router 4. 获取事件路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48210703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com