gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:21:03 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com