如何在具有多个组件的页面中使用React Router?

时间:2015-09-01 10:50:51

标签: javascript reactjs react-router react-jsx

我有这个.js文件,可以创建几个div并渲染一些组件并将它们分配给div。如果它只渲染一个组件,我怎么能在这种情况下使用react路由器?我需要更改此原始文件吗?

HomePage.jsx

import React from 'react';
import 'bootstrap-webpack';

import BigPic from './components/Jumbotron';

import Major from './components/Major';
import Footer from './components/Footer';
import GA from './components/GA';
var gA = require('react-google-analytics');

function googleAnalytics() {
    var ga = document.createElement('div');
    document.body.appendChild(ga);
    React.render(<GA />, ga);
    gA('create', 'UA-XXXX-Y', 'auto');
    gA('send', 'pageview');
}

function jumbotron() {
    //jumbotron
    var wrapper = document.createElement('div');
    //set jumbotron id and class
    wrapper.id = "big";
    wrapper.className = "site-wrapper";
    //append div
    document.body.appendChild(wrapper);
    const jumbotron = document.getElementById('big');
    React.render(<BigPic />, jumbotron);
}

function features() {
    //features
    var feature = document.createElement('div');
    //set features id
    feature.id= "featured-wrapper";
    // append div to body
    document.body.appendChild(feature);
    const major = document.getElementById('featured-wrapper');
     React.render(<Major />, major);
}

function footer() {
    //footer
    var bottom = document.createElement('footer');
    //set footer id
    bottom.id = 'footer';
    bottom.className = "footer-basic-centered";
    //append footer to bottom
    document.body.appendChild(bottom);
    const footer = document.getElementById('footer');
    React.render(<Footer />, footer);
}

function homepage() {
    jumbotron();
    features();
    footer();
    googleAnalytics();
}

homepage();

1 个答案:

答案 0 :(得分:1)

您的主应用程序需要更改为如下所示:

var routes = (
    <Route handler={App} path='/'>
        <Route name='major' handler={Major} path='major'>
    </Route>
);

Router.run(routes, function (Handler) {
  React.render(<Handler/>, document.body);
});

然后,您需要更新App以包含您的jumbotron,页脚和GA代码:

React.createClass({
  render: function(){
    return (
      <div>
        <Jumbotron />
        <RouteHandler />
        <Footer />
        <GA />
      </div>
    );
  }
});

此处的关键位是RouteHandler,因为这将在此处呈现子路由组件。