javascript - 带有 React 高阶组件的 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;
推荐阅读
- r - R中的空间聚类/采样
- azure - 使用 powershell 在 Azure 中创建自动化操作组
- php - phpstan 不通过 strip_tags
- node.js - 从 AWS ElasticBeanstalk node.js 到 AWS ElastiCache Redis 的连接超时
- sap-cloud-sdk - 无法使用其他 ID 创建联系人
- forms - 输入文本时如何更改 PDF 表单字段背景?
- node.js - 使用选项 ALLOW_FIELD_ADDITION 插入缺少字段的 BigQuery(来自 nodeJS)
- api - CKAN:如何使用 api 更新/创建资源的数据字典?
- php - File_get_contents():无法打开流:连接被拒绝
- python - 提取测试pyhon-selenium