使用 Tailwind 改变焦点上的 SVG 颜色

问题描述 投票:0回答:1

我正在创建一个 sidenav,我希望 svg 图标在聚焦时改变颜色,而不是文本颜色

到目前为止我已经创建了这个,但我必须再次重新单击它才能将其设置回默认值,而不是在单击新项目时自动更改

const LinkWithIcon = ({ icon: Icon, text, href }) => {
  const [isSelected, setIsSelected] = useState(false);
  const handleSelect = () => {
    setIsSelected(!isSelected);
  };
  return (
    <div className="">
      <a
        className="flex items-center h-10 gap-3 rounded px-3 py-2 text-muted-foreground hover:text-foreground hover:bg-muted transition-all"
        href={href}
        onClick={handleSelect}
      >
        <Icon className={`h-4 w-4 ${isSelected ? 'text-foreground ' : ''}`} />
        {text}
      </a>
    </div>
  );
};
html reactjs tailwind-css tsx
1个回答
0
投票

您可以使用 onFocus 来实现此目的,

import { useState } from 'react';

const LinkWithIcon = ({ icon: Icon, text, href }) => {
  const [isSelected, setIsSelected] = useState(false);

  const handleFocus = () => {
    setIsSelected(true);
  };

  const handleBlur = () => {
    setIsSelected(false);
  };

  return (
    <div className="">
      <a
        className={`flex items-center h-10 gap-3 rounded px-3 py-2 text-muted-foreground hover:text-foreground hover:bg-muted transition-all ${isSelected ? 'focus:text-foreground' : ''}`}
        href={href}
        onFocus={handleFocus}
        onBlur={handleBlur}
        tabIndex="0"
      >
        <Icon className={`h-4 w-4 ${isSelected ? 'text-foreground ' : ''}`} />
        {text}
      </a>
    </div>
  );
};

export default LinkWithIcon;

我想这就是您所需要的,请告诉我它是否对您有用!

© www.soinside.com 2019 - 2024. All rights reserved.