【问题标题】:onclick menu item active and add class on itonclick 菜单项处于活动状态并在其上添加类
【发布时间】:2023-01-01 21:41:13
【问题描述】:

我想在单击时向我的菜单项添加一个类

<nav className="pt-4">
        {routes.map(({ icon, name, path }) => (
          <ul  >
            <li key={name} className="mb-1">

              <Link to={`/dashboard${path}`} shallow scroll>

                <a className={`block flex gap-4 items-center px-4 py-2 text-xs hover:pl-6 transition-all duration-300
                ${navigate === path ? 'bg-gradient-to-r from-white/10 text-primary' :
                    'text-white hover:text-primary'
                  }
                `}
                >
                  {icon}
                  <span>{name}</span>
                </a>
              </Link>
            </li>

          </ul>
        ))}
      </nav>

我尝试使用 useHistory 但它不再起作用而且我不知道如何使用 useNavigate

【问题讨论】:

    标签: reactjs react-router menu


    【解决方案1】:

    您可以将 Link 组件替换为 NavLink 组件,如下所示:

    <NavLink
        to={`/dashboard${path}`}
        className={`block flex gap-4 items-center px-4 py-2 text-xs hover:pl-6 transition-all duration-300 ${(navData) => (navData.isActive ? 'bg-gradient-to-r from-white/10 text-primary' : 'text-white hover:text-primary')}`}
      >
        {icon}
        <span>{name}</span>
    </NavLink>
    

    【讨论】:

      【解决方案2】:

      这对我有用:

      <NavLink to={`/dashboard${path}`} shallow scroll>
                    {({ isActive }) => (
      
                      <a className={`block flex gap-4 items-center px-4 py-2 text-xs hover:pl-6 transition-all duration-300
                      ${isActive ? 'bg-gradient-to-r from-white/10 text-primary' :
                          'text-white hover:text-primary'
                        }
                      `}
                      >
                        {icon}
                        <span>{name}</span>
                      </a>
                    )}
                    </NavLink>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多