首页 > 解决方案 > 如何通过在 React 中添加 CSS 类来更改状态

问题描述

我想在 React 中旋转一个简单的图标。通过单击一个按钮,它应该以另一种方式旋转。我还在学习反应。在javascript中它更容易一些。您只需将其连接到事件侦听器即可。但不知道如何在反应中做到这一点。

@keyframes infinite-rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.rotate {
  animation: infinite-rotate 2s linear infinite;
}

function RotateIcon() {
return (
<div>
<Icon className="rotate" />
<button>Rotate me</button>
)
}

export default RotateIcon

标签: javascriptcssreactjs

解决方案


最终输出:

在此处输入图像描述

使用状态来跟踪是否旋转元素,基于分配类名,然后在 CSS 文件中应用样式。

import React, { useState } from "react";
import "./style.css";

const Icon = ({ className }) => {
  return <div className={className} />;
};

function RotateIcon() {
  const [rotate, setRotate] = useState(1);
  return (
    <div>
      <Icon
        className={
          rotate % 3 == 1
            ? "rotate-clk icon"
            : rotate % 3 == 2
            ? "rotate-ant icon"
            : "icon"
        }
      />
      <button
        onClick={() => {
          setRotate(rotate + 1);
        }}
      >
        {rotate % 3 == 1
          ? "rotate-anticlowise"
          : rotate % 3 == 2
          ? "stop"
          : "rotate-clockwise"}
      </button>
    </div>
  );
}

export default RotateIcon;

CSS:

h1,
p {
  font-family: Lato;
}
@keyframes infinite-rotate-clk {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes infinite-rotate-ant {
  0% {
    transform: rotate(360deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

.rotate-clk {
  animation: infinite-rotate-clk 2s linear infinite;
}

.rotate-ant {
  animation: infinite-rotate-ant 2s linear infinite;
}


.icon {
  width: 100px;
  height: 100px;
  background-image: linear-gradient(
    45deg,
    #b0f500 25%,
    #000000 25%,
    #000000 50%,
    #b0f500 50%,
    #b0f500 75%,
    #000000 75%,
    #000000 100%
  );
  background-size: 56.57px 56.57px;
  border-radius: 50px;
}

button {
  margin-top: 10px;
  width: 100px;
  height: 50px;
  border-radius: 5px;
  border: 1px solid black;
}

工作应用演示:Stackblitz


推荐阅读