Anime.js 带有 React 高阶组件的动画

Anime.js animation with React's higher order component

我有一个渲染网格的功能组件 elements.I 想通过用 HOC 包装它来为该组件提供 Anime.js 动画。 问题是'How i can implement it in correct way and how i can select desired target element from WrappedComponent ?'.

import React, { PureComponent } from 'react';
import anime from 'animejs/lib/anime.es.js';

function withAnimation(WrappedComponent) {

    return class extends PureComponent {

        handleAnimation = () => {
            anime({
                targets: 'targets are in WrappedComponent',
                translateY: [-30, 0],
                easing: 'easeInOutQuad',
                duration: 2000,
            })
        }

        componentWillMount(){
            this.handleAnimation()
        }

        render() {
            return <WrappedComponent {...this.props}/>;
        }
    };
}


export default withAnimation;

在父组件中创建一个 ref 并将其传递给包装的组件并将其用作 targets :

import React, { PureComponent } from "react";
import anime from "animejs/lib/anime.es.js";

function withAnimation(WrappedComponent) {
  return class extends PureComponent {
    constructor() {
      super();

      // create DOM reference
      this.target1 = React.createRef();
    }

    handleAnimation = () => {
      anime({
        targets: this.target1,
        translateY: [-30, 0],
        easing: "easeInOutQuad",
        duration: 2000
      });
    };

    componentWillMount() {
      this.handleAnimation();
    }

    setTarget = el => {
      this.target1 = el;
    };

    render() {
      return <WrappedComponent setTarget={this.setTarget} {...this.props} />;
    }
  };
}

const WrappedComponent = props => {
  return <div ref={el => props.setTarget(el)}>Animate me</div>;
};

export default withAnimation;