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

时间:2018-12-13 18:11:02

标签: reactjs react-router

我正在使用React,并以一种既有布局组件又有主页组件的方式构造项目。我想根据用户进入的路线来更改页眉组件中页面的标题。

这是我的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;

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

HOC withRouter将为您的组件提供道具matchlocationhistory

然后您可以使用location.pathname来管理组件的呈现