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