React如何实现通知
React 实现通知的方法
使用状态管理
在 React 组件中通过 useState 或 useReducer 管理通知状态,触发状态更新时显示通知。适合简单场景,无需额外依赖。
import { useState } from 'react';
function Notification() {
const [show, setShow] = useState(false);
return (
<div>
<button onClick={() => setShow(true)}>Show Notification</button>
{show && <div className="notification">Message</div>}
</div>
);
}
使用第三方库
借助成熟的库如 react-toastify 或 notistack 快速实现功能丰富的通知系统。支持自定义样式、自动关闭和队列管理。

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function App() {
const notify = () => toast("Notification sent!");
return (
<div>
<button onClick={notify}>Trigger</button>
<ToastContainer />
</div>
);
}
结合 Context API 通过 React Context 全局共享通知状态,跨组件触发显示。适合中大型应用需要多处调用通知的场景。

const NotificationContext = createContext();
function Provider({ children }) {
const [notifications, setNotifications] = useState([]);
const addNotification = (message) => {
setNotifications([...notifications, message]);
};
return (
<NotificationContext.Provider value={{ addNotification }}>
{children}
<div className="notifications">
{notifications.map((msg, i) => <div key={i}>{msg}</div>)}
</div>
</NotificationContext.Provider>
);
}
自定义 Hook 封装 将通知逻辑抽象为自定义 Hook,实现复用和统一管理。例如封装显示时长、动画效果等配置。
function useNotification() {
const [notification, setNotification] = useState(null);
const show = (message, duration = 3000) => {
setNotification(message);
setTimeout(() => setNotification(null), duration);
};
return { notification, show };
}
样式与动画优化 通过 CSS 或动画库(如 Framer Motion)增强视觉体验。添加滑动、淡入淡出等效果提升交互友好度。
.notification {
position: fixed;
bottom: 20px;
right: 20px;
animation: fadeIn 0.3s;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}






