【问题标题】:reactjs dropdown parent menu routing not workingreactjs下拉父菜单路由不起作用
【发布时间】:2021-10-05 09:33:01
【问题描述】:

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

<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 和其他子菜单不起作用,不起作用

【问题讨论】:

    标签: reactjs react-router router tailwind-css


    【解决方案1】:

    首先,它不需要将 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>
      );
    }
    

    【讨论】:

    • 感谢问题已解决,但我在路由器上添加了更多子菜单,但它不起作用。请检查我的问题(更新*)
    • @shawn 将所有子元素移出父元素Router
    • @shawn 我认为我使用的方法对您的目标很方便。请尝试一下,如果有任何问题,请发表评论以获得进一步的贡献。
    • 很高兴听到这个消息。
    • @shawn 是的,我想我不明白你到底想做什么。所以你只需删除参数并将路由与组件一起使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2013-01-21
    • 2017-05-25
    相关资源
    最近更新 更多