【问题标题】:React router dom set active class to the NavLink反应路由器 dom 将活动类设置为 NavLink
【发布时间】:2021-03-30 11:53:18
【问题描述】:

我正在使用 React-router-dom 进行导航

Routes.js

<Router>
      <Switch>
        <Route path="/" exact component={HomePage} activeClassName="routeActive"/>
        <Route path="/login" exact component={Login} activeClassName="routeActive"/>
        <Route path="/category/veg" exact component={Veg} activeClassName="routeActive"/>
        <Route path="/category/non-veg" exact component={NonVeg} activeClassName="routeActive"/>
      </Switch>
    </Router>

然后在我的导航栏组件中我有

<div className="leftNavItems">
          <ul className="navItemsUL">
            <li className="navItemsLI">
              <NavLink to="/" exact className="linkText" activeClassName="routeActive">
                Home
              </NavLink>
            </li>
            <li className="navItemsLI">
              <NavLink to="/login" exact className="linkText" activeClassName="routeActive">
                About us
              </NavLink>
            </li>
            <div className="dropdown">
              {console.log(props)}
              {props.location}
              <span className={` linkText`}>Categories </span>
              <i className="fas fa-caret-down downIcon" />
              <div className="dropdownContent">
                <ul className="dropdownContentUL">
                  <li className="dropdownContentLI">
                    <Link to="/category/:veg" className="dropdownLinkText">
                      Veg
                    </Link>
                  </li>
                  <li className="dropdownContentLI">
                    <Link to="/category/:non-veg" className="dropdownLinkText">
                      Non Veg
                    </Link>
                  </li>
                </ul>
              </div>
            </div>
          </ul>
        </div>

如您所见,我使用“activeClassName”为 Navlink 设置类名,然后在它处于活动状态时更改其颜色,但在某些情况下,我有一个标签“类别”,其中包含一个下拉菜单“veg”和“non-veg”,所以当用户处于 /category/veg 或 /caegory/:non-veg 时,我还需要更改“Category”标签的颜色,因为它是 Navbar 组件控制台.log(props.location) 在这里是未定义的,因为我想它不是 insise。这里有任何其他方式>

【问题讨论】:

    标签: reactjs react-router-dom react-router-v4


    【解决方案1】:

    首先,大约console.log(props.location) 变成undefined,你确定你用withRouter 包裹了组件​​吗?如果它是一个函数组件,你也可以使用钩子let location = useLocation()

    其次,可以像手动控制类名

       <span className={`${props.location.pathname.split('/').includes('category') ? 'routeActive' : 'linkText' }`}>Categories </span>
    

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2018-08-24
      • 1970-01-01
      • 2022-01-21
      • 2017-08-02
      • 2021-02-26
      相关资源
      最近更新 更多