useFlipOver.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { useCallback } from 'react'
  2. import { useEffect } from 'react'
  3. import { useState, useMemo } from 'react'
  4. export const FlipOverEnum = {
  5. UP: 'up',
  6. DOWN: 'down'
  7. }
  8. /**
  9. * @description 用于处理抽屉/弹窗详情中左上角的上下翻页
  10. */
  11. export function useFlipOver(
  12. fn: (id: string) => Promise<void>,
  13. targetId: string,
  14. targetIds: string[] = []
  15. ) {
  16. const [curId, setCurId] = useState('')
  17. useEffect(() => {
  18. setCurId(targetId)
  19. }, [targetId])
  20. const flipConsts = useMemo(() => {
  21. // eslint-disable-next-line react-hooks/rules-of-hooks
  22. const curIndex = targetIds.findIndex(item => item === curId)
  23. if (curIndex !== -1) {
  24. const disableUpBtn = curIndex === 0
  25. const disableDownBtn = curIndex === targetIds.length - 1
  26. const prevId = targetIds[curIndex - 1]
  27. const nextId = targetIds[curIndex + 1]
  28. return { disableUpBtn, disableDownBtn, prevId, nextId, curId }
  29. }
  30. return { disableUpBtn: true, disableDownBtn: true, prevId: '', nextId: '', curId }
  31. }, [curId, targetIds])
  32. const flipFn = async (type: 'up' | 'down') => {
  33. if (type === FlipOverEnum.UP && !flipConsts.disableUpBtn) {
  34. await fn(flipConsts.prevId)
  35. setCurId(flipConsts.prevId)
  36. }
  37. if (type === FlipOverEnum.DOWN && !flipConsts.disableDownBtn) {
  38. await fn(flipConsts.nextId)
  39. setCurId(flipConsts.nextId)
  40. }
  41. }
  42. return { flipFn, flipConsts }
  43. }