【问题标题】:React useState to change icon using fontawesome not updatingReact useState 使用 fontawesome 更改图标不更新
【发布时间】:2021-11-13 21:43:05
【问题描述】:

我正在尝试通过单击图标来更改图标。 isOpen 的值在控制台发生变化,但图标没有变化。

const [isOpen, setIsOpen] = useState(false);

<header className="w-full h-20 shadow-sm">
    <div className="h-full sm:mx-6 md:mx-12 lg:mx-24 xl:mx-48 px-4 xl:px-0">
      <nav className="h-full flex justify-between items-center text-lg">
        <div className="flex items-center">
          <p className="font-bold text-blue z-10">Shaddam</p>
          <figure className="-ml-4 z-0">
            <img src={BrandIconBg} alt="Blob" />
          </figure>
        </div>
        <span
          className="text-blue text-2xl cursor-pointer"
          onClick={() => setIsOpen(!isOpen)}
        >
          <i className={!isOpen ? "fas fa-bars" : "fas fa-times"}></i>
        </span>
      </nav>
    </div>
  </header>

【问题讨论】:

  • 请发个codesandbox好吗。因为问题绝对不在您发送的代码部分。
  • 最好改代码,依赖“isOpen”状态,然后用特定的className渲染相应的图标
  • 这里是代码框codesandbox.io/embed/…
  • idk 为什么在代码和盒子上工作但在本地开发上不起作用
  • 是的。从技术上讲,您在那里没有任何问题,所以它应该可以工作。

标签: reactjs font-awesome use-state


【解决方案1】:

试着改变你的逻辑。此问题背后的原因是图标未显示,因为当您的更改生效时,您的本地开发环境或浏览器未呈现新图标。

const [isOpen, setIsOpen] = useState(false);

<header className="w-full h-20 shadow-sm">
    <div className="h-full sm:mx-6 md:mx-12 lg:mx-24 xl:mx-48 px-4 xl:px-0">
      <nav className="h-full flex justify-between items-center text-lg">
        <div className="flex items-center">
          <p className="font-bold text-blue z-10">Shaddam</p>
          <figure className="-ml-4 z-0">
            <img src={BrandIconBg} alt="Blob" />
          </figure>
        </div>
        <span
          className="text-blue text-2xl cursor-pointer"
          onClick={() => setIsOpen(!isOpen)}
        >
          {isOpen ? 
          <i className="fas fa-bars"></i> :
          <i className="fas fa-times"></i>}
        </span>
      </nav>
    </div>
  </header>

Here 是工作场示例。

【讨论】:

【解决方案2】:

已修复,这是因为我使用 fontawesome cdn 而不是使用 npm 包,当我更改为 npm 包以使其正常工作时

【讨论】:

  • 这个答案被标记为低质量,请提供更多支持信息和解释来更好地回答
猜你喜欢
  • 2020-12-06
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 2021-06-18
相关资源
最近更新 更多