首页 > 解决方案 > reactjs下拉父菜单路由不起作用

问题描述

我已经为下拉子菜单创建了一个路由器,就像

<Route path="/setup" component={Setup}>
     <Route path="/setup/:employee" component={Employee}/>
     <Route path="/setup/:company" component={Company}/>
     <Route path="/setup/:user" component={User}/>
</Route>

当我/setup/employee只使用它会工作但父菜单/setup和其他子菜单不起作用

标签: reactjsreact-routerroutertailwind-css

解决方案


首先,它不需要将 Route 作为孩子添加到另一个。更改您的Route组件,如下所示:

 <Route path="/setup" component={Setup}/>
 <Route path="/setup/:employee" component={Employee}/>

此外,这种使用路由的方法也行不通。假设你要打开/setup/1,因为使用/setup/:employee了上面的/setup/:company路由器/setup/:user,只了解第一个。您无法使用其他参数路由到该地址。怎么router能看懂你发了什么?员工、公司或用户?您应该更改其他路线。您可以只使用一次带有参数的路线样式。但是,如果您想以这种方式做某事,您可以创建一条路线,例如:

<Route path="/setup/:component/:page" component={MyCustomComponent}/>

并实现MyCustomComponent与下面相同的组件:

function MyCustomComponent() {
  let { component, page } = useParams();
  switch (component) {
    case "FirstChild":
      return <FirstChild page={page} />;
    case "SecondCHild":
      return <SecondChild page={page} />;
    default:
      return <NoneOfChildren />;
  }
}

最后,这些是子组件:

function NoneOfChildren(){
  return (
    <div>
      <h3>Nothing have been sent as page!</h3>
    </div>
  );
}

function SecondChild(props) {
  return (
    <div>
      <h3>Second Page: {props.page}</h3>
    </div>
  );
}

function FirstChild(props) {
  return (
    <div>
      <h3>First Page: {props.page}</h3>
    </div>
  );
}

编辑 React 路由器 - URL 参数(分叉)


推荐阅读