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和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...