gpt4 book ai didi

reactjs - 如何使用 React 根据路由更改单独标题组件上的页面标题?

转载 作者:行者123 更新时间:2023-12-03 13:58:35 25 4
gpt4 key购买 nike

我正在使用 React,并以先有布局组件,然后是主页组件的方式构建我的项目。我想根据用户访问的路线更改 header 组件中页面的标题。

这是我的 App.jsx:

import React, { Suspense, lazy, Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Header from './layout/Header.jsx';
import Footer from './layout/Footer.jsx';

const Home = lazy(() => import('./pages/Home.jsx'));
const Weather = lazy(() => import('.pages/Weather.jsx'));
const Encryption = lazy(() => import('./pages/Encryption.jsx'));
const Video = lazy(() => import('./pages/Video.jsx'));

class App extends Component {
render() {
return (
<Router>
<>
<Header/>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/weather" component={Weather}/>
<Route path="/encryption" component={Encryption}/>
<Route path="/video" component={Video}/>
</Switch>
</Suspense>
<Footer/>

</>
</Router>
);
}
}

export default App;

我的 Header.jsx 组件如下所示:

import React, { Component } from 'react';

class Header extends Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>Page Title</h1>
);
}
}

export default Header;

最佳答案

import React, { Component } from "react";
import { withRouter } from "react-router-dom";
class Header extends Component {
constructor(props) {
super(props);
}
render() {
const path = this.props.location.pathname.slice(1);
return (
<div>
<h1>{path}</h1>
</div>
);
}
}

export default withRouter(Header);

此处的工作示例:https://codesandbox.io/s/zl3y72k0pp

关于reactjs - 如何使用 React 根据路由更改单独标题组件上的页面标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53767815/

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