react实现旋转
React 实现旋转效果
在 React 中实现旋转效果可以通过 CSS 动画、内联样式或第三方库完成。以下是几种常见方法:
使用 CSS 动画
定义一个旋转的 CSS 关键帧动画,并通过 className 应用到 React 组件:
/* CSS 文件 */
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spin-animation {
animation: spin 2s linear infinite;
}
// React 组件
import './styles.css';
function SpinningComponent() {
return <div className="spin-animation">旋转元素</div>;
}
使用内联样式
通过动态计算旋转角度并直接应用样式:
import React, { useState, useEffect } from 'react';
function RotatingBox() {
const [angle, setAngle] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setAngle(prev => (prev + 1) % 360);
}, 16);
return () => clearInterval(interval);
}, []);
return (
<div style={{
transform: `rotate(${angle}deg)`,
transition: 'transform 0.1s ease',
width: '100px',
height: '100px',
backgroundColor: 'blue'
}} />
);
}
使用 react-spring 动画库
通过第三方库实现更复杂的动画效果:
import { useSpring, animated } from 'react-spring';
function SpringRotate() {
const props = useSpring({
from: { rotateZ: 0 },
to: { rotateZ: 360 },
loop: true,
config: { duration: 2000 }
});
return (
<animated.div
style={{
width: 100,
height: 100,
backgroundColor: 'red',
...props
}}
/>
);
}
控制旋转状态
通过按钮交互控制旋转的启动/停止:
import React, { useState, useRef } from 'react';
function ControlledRotation() {
const [isRotating, setIsRotating] = useState(false);
const angleRef = useRef(0);
const requestRef = useRef();
const animate = () => {
angleRef.current += 2;
if (angleRef.current >= 360) angleRef.current = 0;
requestRef.current = requestAnimationFrame(animate);
};
useEffect(() => {
if (isRotating) {
requestRef.current = requestAnimationFrame(animate);
} else {
cancelAnimationFrame(requestRef.current);
}
return () => cancelAnimationFrame(requestRef.current);
}, [isRotating]);
return (
<div>
<div
style={{
transform: `rotate(${angleRef.current}deg)`,
width: '80px',
height: '80px',
background: 'green'
}}
/>
<button onClick={() => setIsRotating(!isRotating)}>
{isRotating ? '停止' : '开始'}旋转
</button>
</div>
);
}
性能优化建议
对于复杂场景,考虑使用 CSS 硬件加速:
.optimized-rotate {
transform: rotate(45deg);
will-change: transform;
backface-visibility: hidden;
}
使用 React.memo 避免不必要的重新渲染:
const MemoizedComponent = React.memo(function RotatingItem({ angle }) {
return (
<div style={{ transform: `rotate(${angle}deg)` }}>
{/* 内容 */}
</div>
);
});
以上方法可根据具体需求选择,CSS 动画适合简单场景,JavaScript 控制适合需要精细交互的场景,而动画库则提供更丰富的功能。







