在React和React Router中,如何在除首页之外的每个页面上显示一个header
In React and React Router, how to display a header on every page except home page
我是 React 新手,使用的是 react@16.0.0 和 react-router-dom@4.2.2。
我在每一页上都显示了一个页脚。我想在除主页以外的每个页面上显示一个 header,但我不知道从哪里开始。
我当前的 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>
);
}
}
React Router 将呈现 all 匹配给定路径的路由,因为你没有使用开关。因此,提供路线并将渲染传递给它是一件简单的事情。
例如
<Route path="/" render={ ( props ) => ( props.location.pathname !== "/") && <Header /> }>
用你想要的任何东西(例如/home)替换props.location.pathname检查它有'/'的地方,它不会呈现该路由的组件。
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>
);
}
我是 React 新手,使用的是 react@16.0.0 和 react-router-dom@4.2.2。
我在每一页上都显示了一个页脚。我想在除主页以外的每个页面上显示一个 header,但我不知道从哪里开始。
我当前的 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>
);
}
}
React Router 将呈现 all 匹配给定路径的路由,因为你没有使用开关。因此,提供路线并将渲染传递给它是一件简单的事情。
例如
<Route path="/" render={ ( props ) => ( props.location.pathname !== "/") && <Header /> }>
用你想要的任何东西(例如/home)替换props.location.pathname检查它有'/'的地方,它不会呈现该路由的组件。
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>
);
}