HookModal.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import React, { PropsWithChildren } from 'react';
  2. import ConfirmModal from '../ConfirmModal';
  3. import { get } from 'lodash-es';
  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. const mergedMotion =
  34. typeof motion === 'undefined' || motion ?
  35. {
  36. ...(motion as any),
  37. didLeave: (...args: any[]) => {
  38. const didLeave = get(props.motion, 'didLeave');
  39. if (typeof didLeave === 'function') {
  40. didLeave(...args);
  41. }
  42. afterClose();
  43. },
  44. } :
  45. false;
  46. return (
  47. <ConfirmModal
  48. {...innerConfig}
  49. // visible={!visible ? visible : undefined}
  50. motion={mergedMotion}
  51. />
  52. );
  53. };
  54. export default React.forwardRef<HookModalRef, HookModalProps>(HookModal);