CSSAnimation.tsx 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import React, { CSSProperties, ReactNode } from 'react';
  2. import { isEqual, noop } from "lodash";
  3. interface AnimationEventsNeedBind {
  4. onAnimationStart: (e: React.AnimationEvent) => void
  5. onAnimationEnd: (e: React.AnimationEvent) => void
  6. }
  7. interface AnimationProps {
  8. startClassName?: string;
  9. endClassName?: string;
  10. children: ({}: {
  11. animationClassName: string,
  12. animationStyle: CSSProperties,
  13. animationEventsNeedBind: AnimationEventsNeedBind
  14. }) => ReactNode
  15. animationState: "enter" | "leave"
  16. onAnimationEnd?:()=>void;
  17. onAnimationStart?:()=>void;
  18. }
  19. interface AnimationState {
  20. currentClassName: string
  21. extraStyle: CSSProperties
  22. }
  23. class CSSAnimation extends React.Component<AnimationProps, AnimationState> {
  24. constructor(props) {
  25. super(props);
  26. this.state = {
  27. currentClassName: this.props.startClassName,
  28. extraStyle: {}
  29. };
  30. console.log("===>", this.props);
  31. }
  32. componentDidUpdate(prevProps: Readonly<AnimationProps>, prevState: Readonly<AnimationState>, snapshot?: any) {
  33. const changedKeys = Object.keys(this.props).filter(key => !isEqual(this.props[key], prevProps[key]));
  34. console.log('changedKeys', changedKeys, prevProps, this.props);
  35. if (changedKeys.includes("animationState")) {
  36. // if (this.props.animationState === "enter") {
  37. // this.setState({
  38. // currentClassName: this.props.startClassName,
  39. // extraStyle: {}
  40. // }, this.props.onAnimationStart ?? noop);
  41. // } else {
  42. // this.setState({
  43. // currentClassName: this.props.endClassName,
  44. // extraStyle: {}
  45. // }, this.props.onAnimationEnd ?? noop);
  46. // }
  47. }
  48. if (changedKeys.includes("startClassName")){
  49. this.setState({
  50. currentClassName: this.props.startClassName,
  51. extraStyle: {}
  52. }, this.props.onAnimationStart ?? noop);
  53. }
  54. }
  55. handleAnimationStart = () => {
  56. this.props.onAnimationStart();
  57. }
  58. handleAnimationEnd = () => {
  59. this.setState({
  60. currentClassName: this.props.endClassName,
  61. extraStyle: {}
  62. }, ()=>{
  63. this.props.onAnimationEnd();
  64. });
  65. }
  66. render() {
  67. console.log("mount", this.state.currentClassName);
  68. return this.props.children({
  69. animationClassName: this.state.currentClassName ?? "",
  70. animationStyle: this.state.extraStyle,
  71. animationEventsNeedBind: {
  72. onAnimationStart: this.handleAnimationStart,
  73. onAnimationEnd: this.handleAnimationEnd
  74. }
  75. });
  76. }
  77. }
  78. export default CSSAnimation;