主题
与 React 集成使用
Anime.js 可以方便地与 React 配合,尤其适合:
- 在
useEffect
生命周期中启动动画; - 使用
useRef
获取 DOM 元素; - 配合事件响应(如 onClick)触发动画;
示例:点击按钮使元素移动
jsx
const boxRef = useRef(null);
const handleClick = () => {
anime({
targets: boxRef.current,
translateX: 200,
duration: 1000,
easing: 'easeInOutQuad'
});
};
在 JSX 中绑定事件即可:
jsx
<button onClick={handleClick}>播放动画</button>
小结
Anime.js 可以非常自然地集成到 React 中。推荐在组件内部管理动画逻辑,避免与 React 状态冲突。
示例代码
html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>React 集成 Anime.js</title>
<style>
body {
font-family: sans-serif;
text-align: center;
margin-top: 60px;
}
.box {
width: 80px;
height: 80px;
background-color: #4FC08D;
border-radius: 8px;
margin: 20px auto;
}
button {
padding: 8px 16px;
font-size: 16px;
background-color: #4FC08D;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
}
button:hover {
background-color: #3a9d6f;
}
</style>
</head>
<body>
<div id="root"></div>
<!-- React & ReactDOM -->
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<!-- Babel -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- Anime.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<!-- React App -->
<script type="text/babel">
const { useRef } = React;
function App() {
const boxRef = useRef(null);
const play = () => {
anime({
targets: boxRef.current,
translateX: 250,
duration: 1000,
easing: 'easeInOutQuad'
});
};
return (
<div>
<div ref={boxRef} className="box"></div>
<button onClick={play}>点击播放动画</button>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
</script>
</body>
</html>
✅ 效果说明:
- 使用 React 18 + Babel 编译 JSX;
- 使用
useRef
获取 DOM 元素; - 点击按钮,元素平移动画开始;
- 动画和 React 生命周期完全解耦,适合 SPA 动态组件。