Merging/rendering 单个路由路径中的多个组件

Merging/rendering multiple components in a single Route path

我是 React 的新手,正在尝试将多个组件渲染到单个路由。在 React Router v5 中有 proper/more 有效的方法吗?在我下面的示例代码中,我希望合并 "addCategories" 和 "viewCategories",因为它们将在同一条路线上。

class App extends Component{
render(){
    return(
        <Router>               
            <div>
                <Navbar bg="light" expand="lg">
                    <Navbar.Brand as={Link} to='/'>Asset Management</Navbar.Brand>
                    <Navbar.Toggle aria-controls="basic-navbar-nav" />
                    <Navbar.Collapse id="basic-navbar-nav">
                        <Nav className="mr-auto">
                        <Nav.Link as={Link} to='/'>Home</Nav.Link>  
                        <NavDropdown title="Manage" id="basic-nav-dropdown">
                            <NavDropdown.Item as={Link} to='/manage/category'>Categories</NavDropdown.Item>  
                        </NavDropdown>
                        </Nav>
                    </Navbar.Collapse>
                </Navbar>
                <Route path='/' exact component={Home}/>
                <Route path='/manage/category'component={addCategories}/>
                <Route path='/manage/category'component={viewCategories}/>
            </div>
        </Router>
    )}
}

您可以渲染一个同时渲染 <AddCategories /><ViewCategories /> 的组件。

例如

class Categories extends React.Component {
    render() {
        return (
            <>
                <AddCategories />
                <ViewCategories />
            </>
        )
    }
}

然后在你的路线中 <Route path='/manage/category' component={Categories}/>

React Router 允许您将多个子组件传递给单个 <Route/> 组件。以下将正常工作(并且是 recommended way of constructing routes as of React Router 5.1):

class App extends Component{
  render(){
    return(
      <Router>               
         <div>
            <Navbar bg="light" expand="lg">
              <Navbar.Brand as={Link} to='/'>Asset Management</Navbar.Brand>
                <Navbar.Toggle aria-controls="basic-navbar-nav" />
                  <Navbar.Collapse id="basic-navbar-nav">
                    <Nav className="mr-auto">
                      <Nav.Link as={Link} to='/'>Home</Nav.Link>  
                      <NavDropdown title="Manage" id="basic-nav-dropdown">
                      <NavDropdown.Item as={Link} to='/manage/category'>
                        Categories
                      </NavDropdown.Item>  
                      </NavDropdown>
                    </Nav>
                  </Navbar.Collapse>
                </Navbar>
                <Route path='/' exact component={Home}/>
                <Route path='/manage/category'>
                  <AddCategories />
                  <ViewCategories />
                </Route>
            </div>
        </Router>
    )}
}

请注意,我将您的 Route 组件(使用 component 属性)更改为仅将路由内容指定为子级的 Route 组件。

您必须以 PascalCase 命名您的组件,以便它们被拾取为 React 组件 - 如果您以小写字母开头,它们将被推断为 HTML 个元素!