React实现图标点击旋转:点击切换180deg与0deg状态
Hey there! Implementing a toggle rotation for an icon on click is a really common interaction, and it's straightforward to pull off in React. Let me walk you through a couple of solid approaches:
1. CSS类结合useState(推荐,样式与逻辑分离)
This is my preferred method because it keeps your styling in CSS where it belongs, and the React logic stays clean.
First, set up your CSS with a class that handles the rotated state, plus a transition for smooth animation:
.icon { /* 基础样式,比如大小、颜色 */ font-size: 24px; cursor: pointer; /* 添加过渡让旋转更丝滑 */ transition: transform 0.3s ease; } .icon-rotated { transform: rotate(180deg); }
Then, in your React component, use useState to track the rotation state and toggle it on click:
import { useState } from 'react'; function RotatingIcon() { const [isRotated, setIsRotated] = useState(false); const handleIconClick = () => { setIsRotated(prevState => !prevState); }; return ( <div className={`icon ${isRotated ? 'icon-rotated' : ''}`} onClick={handleIconClick} > {/* 这里可以是你的图标,比如Font Awesome的图标或者自定义SVG */} ↓ </div> ); } export default RotatingIcon;
2. 内联样式直接控制
If you prefer to keep everything in the component (good for simple one-off cases), you can control the transform property directly via inline styles:
import { useState } from 'react'; function RotatingIcon() { const [isRotated, setIsRotated] = useState(false); const handleIconClick = () => { setIsRotated(prev => !prev); }; return ( <div style={{ fontSize: '24px', cursor: 'pointer', transition: 'transform 0.3s ease', transform: isRotated ? 'rotate(180deg)' : 'rotate(0deg)' }} onClick={handleIconClick} > ↓ </div> ); } export default RotatingIcon;
额外小技巧
- 动画平滑度: Always add a
transitionproperty so the rotation doesn't jump abruptly—makes the interaction feel much more polished. - 自定义图标组件: If you're using a third-party icon library (like React Icons), just pass the
onClickhandler and the dynamic class/style to the icon component itself:
import { FaChevronDown } from 'react-icons/fa'; import { useState } from 'react'; function RotatingChevron() { const [isRotated, setIsRotated] = useState(false); return ( <FaChevronDown className={`icon ${isRotated ? 'icon-rotated' : ''}`} onClick={() => setIsRotated(prev => !prev)} size={24} style={{ cursor: 'pointer', transition: 'transform 0.3s ease' }} /> ); }
内容的提问来源于stack exchange,提问作者Learner

