在 React 中使用

在 React 中使用 Anime.js 很简单,只需要结合 React 的 useEffect() 和 Anime.js 的 createScope() 方法即可。

下面的示例展示了如何在 React 代码中直接使用 Anime.js 的方法。

React 示例代码

JavaScript + HTML:

  1. import { animate, createScope, createSpring, createDraggable } from 'animejs';
  2. import { useEffect, useRef, useState } from 'react';
  3. import reactLogo from './assets/react.svg';
  4. import './App.css';
  5. function App() {
  6. const root = useRef(null);
  7. const scope = useRef(null);
  8. const [ rotations, setRotations ] = useState(0);
  9. useEffect(() => {
  10. scope.current = createScope({ root }).add(scope => {
  11. // 所有在这里创建的 anime.js 实例都会被绑定到 <div ref={root}> 上
  12. // 创建一个带有弹性效果的循环动画
  13. animate('.logo', {
  14. scale: [
  15. { to: 1.25, ease: 'inOut(3)', duration: 200 },
  16. { to: 1, ease: createSpring({ stiffness: 300 }) }
  17. ],
  18. loop: true,
  19. loopDelay: 250,
  20. });
  21. // 让 logo 能够以中心点拖拽
  22. createDraggable('.logo', {
  23. container: [0, 0, 0, 0],
  24. releaseEase: createSpring({ stiffness: 200 })
  25. });
  26. // 注册一个动画方法供外部调用
  27. scope.add('rotateLogo', (i) => {
  28. animate('.logo', {
  29. rotate: i * 360,
  30. ease: 'out(4)',
  31. duration: 1500,
  32. });
  33. });
  34. });
  35. // 在组件卸载时清理所有 scope 中的 anime.js 实例
  36. return () => scope.current.revert()
  37. }, []);
  38. const handleClick = () => {
  39. const i = rotations + 1;
  40. setRotations(i);
  41. // 点击按钮时调用 scope 中注册的旋转动画方法
  42. scope.current.methods.rotateLogo(i);
  43. };
  44. return (
  45. <div ref={root}>
  46. <div className="large centered row">
  47. <img src={reactLogo} className="logo react" alt="React logo" />
  48. </div>
  49. <div className="medium row">
  50. <fieldset className="controls">
  51. <button onClick={handleClick}>rotations: {rotations}</button>
  52. </fieldset>
  53. </div>
  54. </div>
  55. )
  56. }
  57. export default App;