index.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. }
  31. componentDidUpdate(prevProps: Readonly<AnimationProps>, prevState: Readonly<AnimationState>, snapshot?: any) {
  32. const changedKeys = Object.keys(this.props).filter(key => !isEqual(this.props[key], prevProps[key]));
  33. if (changedKeys.includes("animationState")) {
  34. }
  35. if (changedKeys.includes("startClassName")){
  36. this.setState({
  37. currentClassName: this.props.startClassName,
  38. extraStyle: {}
  39. }, this.props.onAnimationStart ?? noop);
  40. }
  41. }
  42. handleAnimationStart = () => {
  43. this.props.onAnimationStart();
  44. }
  45. handleAnimationEnd = () => {
  46. this.setState({
  47. currentClassName: this.props.endClassName,
  48. extraStyle: {}
  49. }, ()=>{
  50. this.props.onAnimationEnd();
  51. });
  52. }
  53. render() {
  54. return this.props.children({
  55. animationClassName: this.state.currentClassName ?? "",
  56. animationStyle: this.state.extraStyle,
  57. animationEventsNeedBind: {
  58. onAnimationStart: this.handleAnimationStart,
  59. onAnimationEnd: this.handleAnimationEnd
  60. }
  61. });
  62. }
  63. }
  64. export default CSSAnimation;