在React和React Router中,如何在除主页之外的所有页面上显示标题

Kev*_*dge 2 reactjs react-router-v4

我是React的新手,使用react@16.0.0和react-router-dom@4.2.2。

我在每个页面上都显示一个页脚。我想在首页以外的所有页面上显示标题,但是我不知道从哪里开始。

我当前的app.jsx如下所示:

export default class App extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <Router>
                <div>
                    <Route exact path="/" component={HomePage} />
                    <Route exact path="/download" component={DownloadPage} />
                    <Footer />
                </div>
            </Router>
        );
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 5

由于您没有使用交换机,因此React Router将呈现与给定路径匹配的所有路由。因此,提供路线并向其传递渲染很简单。

例如

<Route path="/" render={ ( props ) => ( props.location.pathname !== "/") && <Header /> }>

将props.location.pathname替换为您想要的内容(例如,/ home),并在其中带有“ /”,并且不会为该路线呈现组件。

render() {
    return (
        <Router>
            <div>
                <Route path="/" render={ ( props ) => ( props.location.pathname !== "/") && <Header /> }>
                <Route exact path="/" component={HomePage} />
                <Route exact path="/download" component={DownloadPage} />
                <Footer />
            </div>
        </Router>
    );
}
Run Code Online (Sandbox Code Playgroud)