reactjs onclick激活的菜单项并在其上添加类

s3fp2yjn  于 2023-01-01  发布在  React
关注(0)|答案(2)|浏览(129)

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

<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

pprl5pva

pprl5pva1#

您可以按如下方式将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>
ehxuflar

ehxuflar2#

这对我很有效

<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>

相关问题