react如何做toast提示
使用 react-hot-toast 库
安装 react-hot-toast 库:
npm install react-hot-toast
在应用的根组件中引入 Toaster 组件:
import { Toaster } from 'react-hot-toast';
function App() {
return (
<div>
<Toaster />
{/* 其他组件 */}
</div>
);
}
在需要显示 toast 的地方调用 toast 方法:
import toast from 'react-hot-toast';
// 基本用法
toast('This is a toast message');
// 成功提示
toast.success('Successfully saved!');
// 错误提示
toast.error('Something went wrong');
// 加载中提示
const loadingToast = toast.loading('Processing...');
// 完成后更新
setTimeout(() => {
toast.dismiss(loadingToast);
toast.success('Done!');
}, 2000);
使用 Chakra UI 的 Toast 组件
安装 Chakra UI:
npm install @chakra-ui/react @emotion/react @emotion/styled framer-motion
设置 ChakraProvider:
import { ChakraProvider } from '@chakra-ui/react';
function App() {
return (
<ChakraProvider>
{/* 其他组件 */}
</ChakraProvider>
);
}
使用 useToast hook:
import { useToast } from '@chakra-ui/react';
function Component() {
const toast = useToast();
const showToast = () => {
toast({
title: 'Toast Title',
description: 'This is a toast description',
status: 'success',
duration: 3000,
isClosable: true,
position: 'top-right'
});
};
return <button onClick={showToast}>Show Toast</button>;
}
自定义 Toast 组件
创建一个可复用的 Toast 组件:
import React, { useState, useEffect } from 'react';
import './Toast.css';
const Toast = ({ message, type, duration = 3000, onClose }) => {
const [visible, setVisible] = useState(true);
useEffect(() => {
const timer = setTimeout(() => {
setVisible(false);
onClose();
}, duration);
return () => clearTimeout(timer);
}, [duration, onClose]);
return visible ? (
<div className={`toast toast-${type}`}>
{message}
</div>
) : null;
};
export default Toast;
使用上下文管理全局 Toast:
import React, { createContext, useContext, useState } from 'react';
import Toast from './Toast';
const ToastContext = createContext();
export const ToastProvider = ({ children }) => {
const [toasts, setToasts] = useState([]);
const addToast = (message, type) => {
const id = Date.now();
setToasts([...toasts, { id, message, type }]);
setTimeout(() => {
removeToast(id);
}, 3000);
};
const removeToast = (id) => {
setToasts(toasts.filter(toast => toast.id !== id));
};
return (
<ToastContext.Provider value={{ addToast }}>
{children}
<div className="toast-container">
{toasts.map(toast => (
<Toast
key={toast.id}
message={toast.message}
type={toast.type}
onClose={() => removeToast(toast.id)}
/>
))}
</div>
</ToastContext.Provider>
);
};
export const useToast = () => {
return useContext(ToastContext);
};
CSS 样式示例
为自定义 Toast 添加基础样式:
.toast-container {
position: fixed;
top: 20px;
right: 20px;
z-index: 1000;
}
.toast {
padding: 12px 24px;
margin-bottom: 10px;
border-radius: 4px;
color: white;
animation: slideIn 0.3s ease-out;
}
.toast-success {
background-color: #48BB78;
}
.toast-error {
background-color: #F56565;
}
.toast-warning {
background-color: #ED8936;
}
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}






