为每个reactJS组件添加组件

Add component to every reactJS component

本文关键字:组件 添加 reactJS      更新时间:2023-09-26

我想把导航栏放在所有页面的顶部。这是路由器:

App = React.createClass({
    render: function() {
        <div>
            <NavBar />
            <Locations hash className="Router">
                <Location path="/" handler={MainPage} />
                <Location path="/help" handler={HelpPage} />
                <Location path="/about" handler={AboutPage} />
                <NotFound handler={NotFoundPage} />
            </Locations>
        </div>
    }
});

注意Locations标签中的哈希参数。当我这样使用路由器时,<NavBar />组件中的链接不使用哈希。但是,如果我在每个单独的组件中包含<NavBar />,那么哈希链接就会像预期的那样工作。是否有一个地方可以包含<NavBar />,以便它在路由器显示的所有页面上呈现?

通过将router从react-router-component切换为react-router解决。

var App = React.createClass({
  render: function() {
    return (
      <div>
        <NavBar />
        {this.props.activeRouteHandler}
      </div>
    );
  }
});
React.renderComponent((
  <Route handler={App}>
    <Route name="main" path="/" handler={MainPage}/>
    <Route name="help" handler={HelpPage}/>
    <Route name="about" handler={AboutPage}/>
    <Route name="notfound" path="*" handler={NotFoundPage}/>
  </Route>
), document.body);