【问题标题】:Conditional routing of components in react jsreact js中组件的条件路由
【发布时间】:2020-09-15 23:38:40
【问题描述】:

我的代码如下所示。我希望以这样一种方式进行路由,即如果有约会路由处于活动状态,那么登录路由链接必须消失。如果登录组件正在路由,则约会路由链接必须消失。我被卡住了。我应该在这里输入什么条件。


            <Link to="/" style={{height:'20px'}}><strong style={{fontSize:'15px' ,color:'#0'}}>Home</strong></Link>
            <Link to="/contact" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Appointment</strong></Link>
            <Link to="/services" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Services</strong></Link>
            <Link to="/Login" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Login For Doctors</strong></Link>
            <Link to="/Appointment" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Todays Appointment</strong></Link>
        </Navigation>

【问题讨论】:

    标签: javascript reactjs routes components


    【解决方案1】:

    您需要检查此文件中的 useLocation() 以了解您当前所在的路径,然后隐藏该路径。

    Here 是一篇展示如何使用 useLocation() 的帖子。然后,您可以使用任何您想要隐藏该链接的方法。一个例子是:

      {location !== '/contact'
          <Link to="/contact" style={{height:'20px'}}><strong style={{fontSize:'15px'}}>Appointment</strong></Link>
           : null}
    

    像这样将位置设置为当前路径后:

    const location = useLocation().pathname
    

    【讨论】:

      【解决方案2】:

      有很多方法可以在 react 中条件渲染组件或 jsx 元素。

      你应该掌握的基本理解是:只要你返回 false 或 false,它就不会渲染。

      您可以使用一些技术,请参阅this article 了解更多信息

      1. 如果有条件
      2. 三元运算符
      3. && 运算符(我个人最喜欢的)
      4. Switch 语句

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-07
        • 2021-05-11
        • 1970-01-01
        • 2020-09-19
        • 1970-01-01
        • 2023-01-13
        • 1970-01-01
        • 2019-01-09
        相关资源
        最近更新 更多