【问题标题】:Anime.js animation with React's higher order component带有 React 高阶组件的 Anime.js 动画
【发布时间】:2019-07-31 12:52:59
【问题描述】:

我有一个渲染网格元素的功能组件。我想通过用 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;

【问题讨论】:

    标签: javascript html css reactjs anime.js


    【解决方案1】:

    在父组件中创建一个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;
    

    【讨论】:

    • 好的,谢谢我发现了问题,突然发现componentWillMount()无法显示元素))
    • 是的,它不会向您显示元素,因为组件尚未安装,您应该改用componentDidMount
    猜你喜欢
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2018-09-14
    • 1970-01-01
    • 2019-04-01
    • 2018-02-06
    • 2019-12-15
    相关资源
    最近更新 更多