React

  1. /**
  2. * @description: 可用于弹框 / 抽屉等
  3. * @author: NHF
  4. */
  5. import { useState, useCallback } from 'react';
  6. export interface DetailState<T, U> {
  7. visible: boolean;
  8. data: T;
  9. type?: U;
  10. }
  11. export interface DetailActions<T, U> {
  12. show?: (data?: T, type?: U) => void;
  13. hide?: () => void;
  14. setState?: React.Dispatch<React.SetStateAction<DetailState<T, U>>>;
  15. }
  16. const useDetail = <T, U = BaseModalType>(
  17. initialState: T = {} as T,
  18. type?: U,
  19. ): [DetailState<T, U>, DetailActions<T, U>] => {
  20. const [state, setState] = useState<DetailState<T, U>>({
  21. type,
  22. visible: false,
  23. data: initialState,
  24. });
  25. const show = useCallback(
  26. (data?: T, showType?: U) => {
  27. setState({
  28. type: showType,
  29. visible: true,
  30. data: data as T,
  31. });
  32. },
  33. [setState],
  34. );
  35. const hide = useCallback(() => {
  36. setState({
  37. type: undefined,
  38. visible: false,
  39. data: initialState,
  40. });
  41. }, [setState, initialState]);
  42. return [state, { show, hide, setState }];
  43. };
  44. export default useDetail;