react实现Toast组件
实现Toast组件的基本思路
Toast组件通常用于显示临时性的提示信息,几秒后自动消失。React中可以通过状态管理和动画效果实现。
创建Toast组件文件
新建Toast.js文件,定义基础组件结构:
import React, { useState, useEffect } from 'react';
import './Toast.css';
const Toast = ({ message, duration = 3000, onClose }) => {
const [visible, setVisible] = useState(true);
useEffect(() => {
const timer = setTimeout(() => {
setVisible(false);
onClose && onClose();
}, duration);
return () => clearTimeout(timer);
}, [duration, onClose]);
return visible ? (
<div className="toast">
{message}
</div>
) : null;
};
export default Toast;
添加CSS样式
创建Toast.css文件添加基础样式:

.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 12px 24px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
border-radius: 4px;
animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
创建Toast管理器
为了实现全局调用,创建ToastManager.js:
import React, { useState } from 'react';
import Toast from './Toast';
let toastCount = 0;
export const ToastContext = React.createContext();
export const ToastProvider = ({ children }) => {
const [toasts, setToasts] = useState([]);
const addToast = (message, duration) => {
const id = toastCount++;
setToasts([...toasts, { id, message, duration }]);
};
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}
duration={toast.duration}
onClose={() => removeToast(toast.id)}
/>
))}
</div>
</ToastContext.Provider>
);
};
在应用中使用
在根组件中包裹ToastProvider:

import React from 'react';
import { ToastProvider } from './ToastManager';
function App() {
return (
<ToastProvider>
{/* 其他应用内容 */}
</ToastProvider>
);
}
调用Toast的方法
在任意子组件中通过context调用:
import React, { useContext } from 'react';
import { ToastContext } from './ToastManager';
function SomeComponent() {
const { addToast } = useContext(ToastContext);
const showToast = () => {
addToast('操作成功', 2000);
};
return (
<button onClick={showToast}>显示Toast</button>
);
}
可选的功能扩展
- 支持不同类型:添加success/warning/error等样式变体
- 自定义位置:允许设置top/middle/bottom等显示位置
- 队列管理:当多个Toast同时触发时实现队列显示
- 自定义动画:提供更多动画效果选项
- 手动关闭:允许用户点击关闭Toast
实现多类型Toast示例
修改Toast组件支持不同类型:
const Toast = ({ message, type = 'info', duration = 3000, onClose }) => {
// ...其他代码不变
return visible ? (
<div className={`toast toast-${type}`}>
{message}
</div>
) : null;
};
添加对应的CSS样式:
.toast-info {
background-color: rgba(0, 0, 0, 0.7);
}
.toast-success {
background-color: rgba(40, 167, 69, 0.9);
}
.toast-error {
background-color: rgba(220, 53, 69, 0.9);
}






