gongxiangp2/hooks/useToast.ts

48 lines
1006 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use client'
import { useState, useCallback } from 'react'
interface ToastOptions {
variant?: 'success' | 'error'
duration?: number // 显示时长(毫秒),默认2000ms
}
export function useToast() {
const [toast, setToast] = useState<{
message: string
variant: 'success' | 'error'
show: boolean
} | null>(null)
const showToast = useCallback((message: string, options?: ToastOptions) => {
setToast({
message,
variant: options?.variant || 'success',
show: true,
})
const duration = options?.duration || 2000
setTimeout(() => {
setToast((prev) => prev ? { ...prev, show: false } : null)
// 动画结束后清除
setTimeout(() => {
setToast(null)
}, 300)
}, duration)
}, [])
const hideToast = useCallback(() => {
setToast((prev) => prev ? { ...prev, show: false } : null)
setTimeout(() => {
setToast(null)
}, 300)
}, [])
return {
toast,
showToast,
hideToast,
}
}