React Hot Toast 使用教程
项目介绍
React Hot Toast 是一个轻量级、可定制且美观的 React 通知库。它以其简洁的设计和易于使用的 API 而受到开发者的喜爱。React Hot Toast 提供了热默认的通知样式,易于定制,支持 Promise API,并且体积小巧,不到 5KB。
项目快速启动
安装
你可以使用 Yarn 或 NPM 来安装 React Hot Toast:
# 使用 Yarn
yarn add react-hot-toast
# 使用 NPM
npm install react-hot-toast
基本使用
在你的 React 应用中添加 Toaster 组件,并从任何地方触发 toast()
函数:
import React from 'react';
import toast, { Toaster } from 'react-hot-toast';
const notify = () => toast('Here is your toast');
const App = () => {
return (
<div>
<button onClick={notify}>Make me a toast</button>
<Toaster />
</div>
);
};
export default App;
应用案例和最佳实践
自定义样式
React Hot Toast 允许你轻松自定义通知的样式。你可以通过传递一个函数来定制每个通知的外观:
import toast from 'react-hot-toast';
const customToast = () => toast.custom((t) => (
<div style={{ background: 'blue', color: 'white' }}>
Custom Toast - {t.message}
</div>
));
const App = () => {
return (
<div>
<button onClick={customToast}>Make a custom toast</button>
<Toaster />
</div>
);
};
使用 Promise API
React Hot Toast 支持从 Promise 自动生成加载器和通知:
import toast from 'react-hot-toast';
const fetchData = () => new Promise((resolve) => {
setTimeout(resolve, 2000);
});
const promiseToast = () => toast.promise(fetchData, {
loading: 'Loading...',
success: 'Got the data',
error: 'Error when fetching',
});
const App = () => {
return (
<div>
<button onClick={promiseToast}>Fetch Data</button>
<Toaster />
</div>
);
};
典型生态项目
React Hot Toast 可以与许多其他 React 生态项目集成,例如:
- Redux: 在 Redux 操作中触发通知。
- Next.js: 在 Next.js 应用中使用服务器端渲染的通知。
- Material-UI: 与 Material-UI 组件库结合使用,以获得一致的视觉风格。
这些集成可以帮助你构建更加丰富和一致的用户体验。