首页 文章

组件未使用react-router进行渲染

提问于
浏览
2

我制作了一些路线,但是当我点击链接时,我的组件无法渲染 . 我没有得到任何错误,组件,除了Navbar,根本不渲染 . BrowswerHistory产生相同的结果 . 我正在使用react-router 3.0.0版本 . 我的路由器结构有什么问题?

import {Router, Route, IndexRoute,  hashHistory} from 'react-router';

const router = (
    <Router history={hashHistory}>
        <Route path="/" component={Navbar}>
            <IndexRoute  component={Main}></IndexRoute>
            <Route path="other" component={Other}></Route>
            <Route path="aboutus" component={AboutUs}></Route>
        </Route>
    </Router>
    );


   ReactDOM.render(
    router,
     document.getElementById('root')
   );

导航栏组件:

import React from 'react';
import {Link} from 'react-router';
class Navbar extends React.Component {
render() {
return (
 <nav>
  <ul className="menu-list">
    <li className="menu-item">
      <Link to="/" className="menu-link">Main</Link>
    </li>
    <li className="menu-item">
      <Link to="aboutus" href="" className="menu-link">About Us</Link>
    </li>
    <li className="menu-item">
      <Link to="other" className="menu-link">Some other item</Link>
    </li>
  </ul>
 </nav>
  );
 }
}

 export default Navbar;

1 回答

  • 0

    因为你忘记了这一部分: {this.props.children} . 您需要指定您想要的地方 render 您的子组件 .

    Reason why this is requiredNavBar 是主要组件,所有其他组件都在 render 里面,所以你需要使用 {this.props.children} ,在这个地方子组件将 render .

    用这个:

    return (
      <nav>
        <ul className="menu-list">
    
          <li className="menu-item">
            <Link to="/" className="menu-link">Main</Link>
          </li>
    
          <li className="menu-item">
            <Link to="aboutus" href="" className="menu-link">About Us</Link>
          </li>
    
          <li className="menu-item">
            <Link to="other" className="menu-link">Some other item</Link>
          </li>
    
        </ul>
        {this.props.children} //added this line
      </nav>
    );
    

相关问题