javascript - Anime.js 动画与 React 的高阶组件

标签 javascript html css reactjs anime.js

我有一个呈现网格元素的功能组件。我想通过用 HOC 包装它来为该组件提供 Anime.js 动画。 问题是“我如何以正确的方式实现它以及如何从 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;

关于javascript - Anime.js 动画与 React 的高阶组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57291204/

相关文章:

javascript - 使用 Kendo UI 上传控件将请求 header 添加到 XmlHttpRequest

javascript - 如何在javascript中创建列表字典

javascript - 如何防止图像动画穿过我的整个屏幕而不仅仅是我的容器?

html - 图像溢出到 div 之外

javascript - 如何从子窗口jquery调用父窗口函数?

javascript - 当到达 HTML 文件中的某个点时动画数字和文本

html - 为什么内部容器溢出父容器并改变其位置?

jquery - 一个div在右边,一个在左边,宽度固定

ios - 知道用户何时以全屏模式使用应用程序? (iOS)

html - 崩溃 margin 问题