| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- import { useCallback } from 'react'
- import { useEffect } from 'react'
- import { useState, useMemo } from 'react'
- export const FlipOverEnum = {
- UP: 'up',
- DOWN: 'down'
- }
- /**
- * @description 用于处理抽屉/弹窗详情中左上角的上下翻页
- */
- export function useFlipOver(
- fn: (id: string) => Promise<void>,
- targetId: string,
- targetIds: string[] = []
- ) {
- const [curId, setCurId] = useState('')
- useEffect(() => {
- setCurId(targetId)
- }, [targetId])
- const flipConsts = useMemo(() => {
- // eslint-disable-next-line react-hooks/rules-of-hooks
- const curIndex = targetIds.findIndex(item => item === curId)
- if (curIndex !== -1) {
- const disableUpBtn = curIndex === 0
- const disableDownBtn = curIndex === targetIds.length - 1
- const prevId = targetIds[curIndex - 1]
- const nextId = targetIds[curIndex + 1]
- return { disableUpBtn, disableDownBtn, prevId, nextId, curId }
- }
- return { disableUpBtn: true, disableDownBtn: true, prevId: '', nextId: '', curId }
- }, [curId, targetIds])
- const flipFn = async (type: 'up' | 'down') => {
- if (type === FlipOverEnum.UP && !flipConsts.disableUpBtn) {
- await fn(flipConsts.prevId)
- setCurId(flipConsts.prevId)
- }
- if (type === FlipOverEnum.DOWN && !flipConsts.disableDownBtn) {
- await fn(flipConsts.nextId)
- setCurId(flipConsts.nextId)
- }
- }
- return { flipFn, flipConsts }
- }
|