在交换机内部的同一路径中显示两个组件

时间:2019-07-18 13:39:18

标签: javascript react-router-v4 react-router-dom

我需要设置一个switch来显示容器组件和一个login表单,当用户未在每个主要组件上通过身份验证时。

我找到了另一个解决方案,该解决方案告诉您将两个组件包装在div中,以便在开关中的同一path中使用它。但是问题是我的某些组件使用了req.params路径,当它们包裹在div

中时没有传递给组件
    function Routes(props) {

    const noLoggedIn = [
        {
            path: "/",
            exact: true,
            component: () =>    <div> 
                                    <EventsListContainer /> 
                                    <LoginFormContainer /> 
                                </div>
        },
        {
            path: "/events/:id",
            exact: false,
            component: () =>    <div> 
      //when the component is mounted it doesn't get the :id
                                    <EventDetailsContainer />
                                    <LoginFormContainer /> 
                                </div>
        }
    ]
      return (<div>
    {!props.authenticated && 
      <Switch>
        {noLoggedIn.map((route, index) =>
                <Route
                  key={index}
                  path={route.path}
                  exact={route.exact}
                  component={route.component}
                />
        )}
      </Switch>}

    {props.authenticated && 
      <Switch>
        <Route exact path="/" component={EventsListContainer} />
        <Route exact path="/" component={CreateEventFormContainer} />
      //here the component gets the :id
        <Route path="/events/:id" component={EventDetailsContainer} />
        <Route path="/events/:id" component={CreateTicketFormContainer} />

      </Switch> }
  </div>)
}

1 个答案:

答案 0 :(得分:0)

尝试如下-

<Route path='/some-path' render={props =>
  <div>
    <FirstChild />
    <SecondChild />
  </div>
} />

您也可以按照以下方式进行操作-

render((
  <Router>
    <Route path="/" 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>
  </Router>
), node)

class App extends React.Component {
  render() {
    // the matched child route components become props in the parent
    return (
      <div>
        <div className="Main">
          {/* this will either be <Groups> or <Users> */}
          {this.props.main}
        </div>
        <div className="Sidebar">
          {/* this will either be <GroupsSidebar> or <UsersSidebar> */}
          {this.props.sidebar}
        </div>
      </div>
    )
  }
}

class Users extends React.Component {
  render() {
    return (
      <div>
        {/* if at "/users/123" this will be <Profile> */}
        {/* UsersSidebar will also get <Profile> as this.props.children.
            You can pick where it renders */}
        {this.props.children}
      </div>
    )
  }
}

示例-https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#named-components