HookModal.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import React, { PropsWithChildren } from 'react';
  2. import ConfirmModal from '../ConfirmModal';
  3. import { get } from 'lodash';
  4. import { ConfirmProps } from '../confirm';
  5. import { Motion } from '../../_base/base';
  6. interface HookModalProps {
  7. afterClose: (...args: any[]) => void;
  8. config: ConfirmProps;
  9. motion?: Motion;
  10. }
  11. export interface HookModalRef {
  12. destroy: () => void;
  13. update: (newConfig: ConfirmProps) => void
  14. }
  15. // eslint-disable-next-line max-len
  16. const HookModal = ({ afterClose, config, ...props }: PropsWithChildren<HookModalProps>, ref: React.Ref<any>) => {
  17. const [innerConfig, setInnerConfig] = React.useState(config);
  18. React.useImperativeHandle(ref, () => ({
  19. destroy: () => {
  20. setInnerConfig(originConfig => ({
  21. ...originConfig,
  22. visible: false,
  23. }));
  24. },
  25. update: newConfig => {
  26. setInnerConfig(originConfig => ({
  27. ...originConfig,
  28. ...newConfig,
  29. }));
  30. },
  31. }));
  32. const { motion } = props;
  33. /* istanbul ignore next */
  34. const mergedMotion =
  35. typeof motion === 'undefined' || motion ?
  36. {
  37. ...(motion as any),
  38. didLeave: (...args: any[]) => {
  39. const didLeave = get(props.motion, 'didLeave');
  40. if (typeof didLeave === 'function') {
  41. didLeave(...args);
  42. }
  43. afterClose();
  44. },
  45. } :
  46. false;
  47. return (
  48. <ConfirmModal
  49. {...innerConfig}
  50. // visible={!visible ? visible : undefined}
  51. motion={mergedMotion}
  52. />
  53. );
  54. };
  55. export default React.forwardRef<HookModalRef, HookModalProps>(HookModal);