【问题标题】:Can I add active class when url starts a string in react Navlink?当 url 在反应 Navlink 中启动字符串时,我可以添加活动类吗?
【发布时间】:2019-10-09 05:53:18
【问题描述】:

当 url 以“/teacher/create/”字符串开头时,如何在 react navlink 中添加活动类?

【问题讨论】:

    标签: reactjs navigation


    【解决方案1】:
    <NavLink to={"/teacher/create/"} exact activeClassName={this.props.location.pathname.startsWith("/teacher/create/") && "activeLink"}>{title}</NavLink>
    

    并添加css:

    .activeLink {
        color: red;
    }
    

    【讨论】:

      【解决方案2】:
      <NavLink to={"/teacher/create/2"} exact activeClassName={this.props.location.pathname === "/teacher/create/2" && "activeLink"}>{title}</NavLink>
      

      并添加css:

      .activeLink {
          color: red;
      }
      

      react-router-dom: "^4.1.2"

      【讨论】:

        【解决方案3】:

        我不知道上述其他解决方案是如何工作的,但就我而言,我无法访问 this.props.location。你可以通过尝试这样的方式来做到这一点:

        export const LooseNavLink = props => (
          <NavLink {...props} isActive={(match, location) => location.pathname.startsWith(props.to.pathname)}/>
        )
        

        【讨论】:

          猜你喜欢
          • 2020-03-02
          • 2020-02-03
          • 2021-01-04
          • 2016-05-25
          • 1970-01-01
          • 1970-01-01
          • 2021-03-30
          • 2022-09-23
          • 2021-11-21
          相关资源
          最近更新 更多