javascript - 如何通过在 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
解决方案
最终输出:
使用状态来跟踪是否旋转元素,基于分配类名,然后在 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
推荐阅读
- r - R根据条件从具有特定ID的数据框中删除所有行
- angular - 如何在 Angular 中绑定 json 文件中的多个特定值?
- reactjs - 当使用具有不同道具的路由组件时重复
- react-native - 我想改变导航图标的颜色,我该怎么做?
- python-3.x - 在 TF-Agents 中使用 EpisodicReplayBuffer
- sql - Regexp_Substr 过滤 SQL 中的行
- vue.js - 为什么 vue3 不必要地重新渲染 v-for 中的节点?
- wordpress - 仅当用户是管理员时才显示 add_filter
- java - CompletionException:client.HttpClientErrorException: 400 和服务器端 HTTP 请求解析错误 RFC 7230 并已被忽略
- javascript - 文本区域的更改事件