简体   繁体   中英

React Router - Nested Components will not Render

I have a standard react component created with create-react-app . I am trying to render different components using Link s.

Here is my App.js :

import React, { Component } from 'react';
import { Router, Route, browserHistory } from 'react-router'
import Header from './Header';
import One from './One';
import Two from './Two';
import Three from './Three';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <div className="App">
        <Router history={browserHistory} >
          <Route component={Header} path="/" >
            <Route component={One} path="one" name="One" />
            <Route component={Two} path="two" name="Two" />
            <Route component={Three} path="three" name="Three" />
          </Route>
        </Router>
      </div>
    );
  }
}

export default App;

Here is the Header.js :

import React, { Component } from 'react';
import { Link } from 'react-router'
import './App.css';

class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };

  }

  render() {
    return (
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/one">One</Link></li>
        <li><Link to="/two">Two</Link></li>
        <li><Link to="/three">Three</Link></li>
      </ul>
    );
  }
}

export default Header;

Here is One.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };

  }

  render() {
    return (
      <h1>One</h1>
    );
  }
}

export default App;

I click on one of the links, the address bar changes, but no components will render inside of the nested route. I can remove the nesting:

<Router history={browserHistory} >
  <Route component={Header} path="/" />
  <Route component={One} path="one" name="One" />
  <Route component={Two} path="two" name="Two" />
  <Route component={Three} path="three" name="Three" />
</Router>

Which will render the components but the Header is no longer rendered.

What am I missing?

You forgot this part in Header component:

this.props.children

You need to define the place where you want to render your child components, Use this:

render() {
    return (
     <div>
        <ul>
           <li><Link to="/">Home</Link></li>
           <li><Link to="/one">One</Link></li>
           <li><Link to="/two">Two</Link></li>
           <li><Link to="/three">Three</Link></li>
        </ul>
        {this.props.children}
      </div>
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM