呀哈!
剛認識這些彈出式提醒工具的我,曾忍不住問了 Chatgpt 為什麼他們會取跟吐司相關的名稱。
Chatgpt 表示:React Hot Toast 和 Toastify 的名字都帶有一種「熱吐司」的感覺,這種命名方式既輕鬆有趣,又有強烈的視覺聯想。這些名字特別適合彈出式通知工具,因為它們像熱騰騰的吐司一樣,快速出現並溫暖地提醒用戶。
於是我的腦袋又出現奇怪的東西:
好啦,廢話不多說,先來介紹第一個工具,React-Hot-Toast (v2.4.1)~上菜!!
烤得恰恰好的吐司的魔法第一步:在 VS code 打開專案,打開終端機,輸入安裝指令,並在專案中導入。
npm install react-hot-toast
import toast, { Toaster } from 'react-hot-toast';
烤得恰恰好的吐司的魔法第二步:拿出吐司 toast()
您好!您的原味吐司!
toast('Here is your classic toast.');
當然,送入烤箱前,也可以先定義好每片吐司的配料,如下:
toast('Hello World', { //通知顯示的字串內容
duration: 4000, //通知持續的時間為為4000毫秒
position: 'top-center', //通知的顯示位置為畫面上方的正中間
// Styling
style: {}, //可以修改通知外觀,在這裡指定 CSS 樣式,例如 backgroundColor, color 等
className: '', //可以在這裡設置一個自定義的 class 來修改通知的外觀樣式
// Custom Icon
icon: '', //自定義通知中的圖標
// Change colors of success/error/loading icon
iconTheme: { //用來改變通知圖標顏色的選項
primary: '#000',
secondary: '#fff',
},
// Aria
ariaProps: { //這個選項是為了確保通知對於無障礙技術(如螢幕閱讀器)是友好的
role: 'status',
'aria-live': 'polite',
},
});
“難道就沒有搭配好的預設組合,讓我選就好了嗎?”
當然有囉~請見菜單:
成功
toast.success('Successfully created!');
失敗
toast.error('This is an error!');
自定義
吐司裡面可以加入 JSX 結構,且這個通知並不會有預設樣式 (原味吐司都還有預設樣式的說~)
toast.custom(<div>Hello World</div>);
Loading
這個比較少使用,因為 Loading 狀態結束之後,通常狀態會更新為成功或失敗,所以 Promise 的組合更好使用。
Promise
const myPromise = fetchData();
toast.promise(myPromise, {
loading: 'Loading',
success: 'Got the data',
error: 'Error when fetching',
});
這些菜單中的選項,要另外修改樣式也是可以的喔!
<Toaster
position="top-center" //default
reverseOrder={false} //default
gutter={8} //default
containerClassName="" //default
containerStyle={{}} //default
toastOptions={{
// Define default options
className: '',
duration: 5000,
style: {
background: '#363636',
color: '#fff',
},
// Default options for specific types
success: {
duration: 3000,
theme: {
primary: 'green',
secondary: 'black',
},
},
error: {
duration: 4000, // You can set a different duration for error notifications
style: {
background: 'red', // Error notifications will have a red background
color: '#fff',
},
theme: {
primary: 'white',
secondary: 'red',
},
},
}}
/>
React Hot Toast 的部分先暫時到這裡,更細節的設定可以看看官方文件~我出發去烤肉啦~