onclick 按钮切换图标在 reactjs 中不起作用

onclick button toggle icon not working in reactjs

这里我尝试在点击按钮时切换反应图标,但它仍然不起作用:

这是我的代码:

const [anchorEl, setAnchorEl] = useState(null);

  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

   <button onClick={handleClick} className="top-rated-car-react-button">
            {anchorEl ? (
              <MdFavoriteBorder
                style={{
                  color: "#F76631", 
                }}
              />
            ) : (
              <MdFavorite
                style={{
                  color: "#F76631",
                }}
              />
            )}
   </button>

我尝试使用 React 图标按钮的 onClick 事件,但如果 MdFavoriteBorder 它应该随着 MdFavorite 改变,当点击按钮时与 MdFavorite 活动改变时相同,它不会与两个图标切换MdFavoriteBorder

看起来太复杂了。我会创建一个布尔状态,然后像这样切换它:

import { useState } from "react";
import { MdFavorite, MdFavoriteBorder } from "react-icons/md";

export default function App() {
  const [favorite, setFavorite] = useState(false);
  const toggleFavorite = () => setFavorite((prev) => !prev);

  return (
    <button onClick={toggleFavorite} className="top-rated-car-react-button">
      {favorite ? (
        <MdFavoriteBorder style={{ color: "#F76631" }} />
      ) : (
        <MdFavorite style={{ color: "#F76631" }} />
      )}
    </button>
  );
}

https://codesandbox.io/s/cool-poincare-wm1ite

您可以像

这样简单的方法来做到这一点

const [changeIcon, setChangeIcon] = useState(true);
  const handleClick = (event) => {
    setAnchorEl(!changeIcon);
  };

   <button onClick={handleClick} className="top-rated-car-react-button">
            {changeIcon ? (
              <MdFavoriteBorder
                style={{
                  color: "#F76631", 
                }}
              />
            ) : (
              <MdFavorite
                style={{
                  color: "#F76631",
                }}
              />
            )}
   </button>

单击 setChangeIcon 时,会根据之前的状态将 changeIcon 的值设置为 false 或 true,组件将重新加载,图标将切换