Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I just started learning React, I'm trying to make a SPA blog, which has a global positioned fixed header.

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'));

So, each routes has the same header and from my angular background, I would use header outside ui-view.

Its a good practice to import the header component in each individual page component, or can I add the header component on my <Router><myHeader/><otherRoutes/></Router>?

Update:

I was thinking to use something like this:

Routes component, where I define my routes:

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>
        )
    }
}

And then on main Index.js file I would like to render something like:

import Routes from './components/Routes';

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

Can someone explain me? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

From my experience it can be good to define a layout component for your page, something like...

Layout Component

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

You then import layout into each of your page components...

Contact Page Component

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

And you can leave your routing the same, your route will render the contact page and in turn will render your header.

This way you get control of repetitive stuff that will be on multiple pages, if you need one or two slightly different pages you can just create another layout and use that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...