reactjs – 使用React-Router,每页有一个布局页面或多个组件

前端之家收集整理的这篇文章主要介绍了reactjs – 使用React-Router,每页有一个布局页面或多个组件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
添加反应路由器到现有项目。

目前,一个模型被传递给一个根组件,它包含一个用于子导航的导航组件和一个主组件。

反应路由器的例子我发现只有一个子组件,什么是最好的方式有多个子组件更改,而不重复布局代码在两个?

如果我正确理解你,实现你将在你的Route中定义多个组件。你可以使用它像( example from the docs):
// think of it outside the context of the router,if you had pluggable
// portions of your `render`,you might do it like this
<App children={{main: <Users/>,sidebar: <UseRSSidebar/>}}/>

// So with the router it looks like this:
const routes = (
  <Route component={App}>
    <Route path="groups" components={{main: Groups,sidebar: GroupsSidebar}}/>
    <Route path="users" components={{main: Users,sidebar: UseRSSidebar}}>
      <Route path="users/:userId" component={Profile}/>
    </Route>
  </Route>
)

class App extends React.Component {
  render () {
    const { main,sidebar } = this.props;
    return (
      <div>
        <div className="Main">
          {main}
        </div>
        <div className="Sidebar">
          {sidebar}
        </div>
      </div>
    )
  }
}

class Users extends React.Component {
  render () {
    return (
      <div>
        {/* if at "/users/123" `children` will be <Profile> */}
        {/* UseRSSidebar will also get <Profile> as this.props.children,so its a little weird,but you can decide which one wants
            to continue with the nesting */}
        {this.props.children}
      </div>
    )
  }
}

也检查了sidebar example app,应该帮助你更多。

编辑:
根据@ Luiz的评论

In the latest version of router the components are in the root of the props object

所以:

const { main,sidebar } = this.props.children;

变为:

const { main,sidebar } = this.props;

猜你在找的React相关文章