小编典典

反应路由器全局头

reactjs

我刚刚开始学习React,我试图创建一个SPA博客,该博客具有全局定位的固定标头。

import React from 'react';
import { render } from 'react-dom';
// import other components here

    render((
      <Router history={browserHistory}>
        <Route path="/" component={Home} />
        <Route path="/About" component={About} />
        <Route path="/Contact" component={Contact} />
        <Route path="*" component={Error} />
      </Router>
    ), document.getElementById('app'));

因此,每条路线都具有相同的标题,并且从我的角度背景来看,我将在ui-view之外使用标题。

在每个单独的页面组件中导入标头组件是一个好习惯,还是可以在我的标头组件上添加标头组件<Router><myHeader/><otherRoutes/></Router>

更新:

我当时在想使用这样的东西:

路线组件,我在其中定义路线:

class Routes extends React.Component {
    render() {
        return (
            <Router history={browserHistory}>
                <IndexRoute component={Home} />
                <Route path="/studio" component={Studio} />
                <Route path="/work" component={Work} />
                <Route path="*" component={Home} />
            </Router>
        )
    }
}

然后在主要的Index.js文件上,我想呈现如下内容:

import Routes from './components/Routes';

render((
   <div>
      <div className="header">header</div>
      <Routes />
   </div>
), document.getElementById('app'));

有人可以向我解释吗?谢谢!


阅读 208

收藏
2020-07-22

共1个答案

小编典典

根据我的经验,最好为页面定义布局组件,例如…

布局组件

render() {
    return(
       <div>
          <Header />
             { this.props.children }
             /* anything else you want to appear on every page that uses this layout */
          <Footer />
       </div>
    );
}

然后,您将布局导入到每个页面组件中…

联系页面组件

render() {
    return (
        <Layout>
           <ContactComponent />
           /* put all you want on this page within the layout component */
        </Layout>
    );
}

您可以保持路由不变,您的路由将呈现联系页面,并依次呈现标题。

这样,您就可以控制将要出现在多个页面上的重复内容,如果需要一个或两个稍有不同的页面,则可以创建另一个布局并使用它。

2020-07-22