跳過到頁腳內容
NODE 說明

toastify npm(開發者的使用方法)

在現代網頁開發中,及時向用戶提供反饋對於無縫的用戶體驗至關重要。 吐司通知是一種有效的消息傳遞方式,不會中斷用戶的工作流程。 React-toastify 套件因其簡單和靈活性而成為在 React 應用程式中實現吐司通知的熱門選擇。 我們還將研究 IronPDF NPM 包,用於生成、編輯和管理 PDF 文檔。 This article will guide you through the process of integrating React-toastify and IronPDF into your React project.

什麼是 Toastify?

React-toastify 是一個 NPM 套件,使您能夠在 React 應用中添加自定義的吐司通知,且設置極少。它提供了各種功能,包括不同的通知類型、自動關閉功能、自定義樣式等。

toastify npm (如何為開發者工作):圖1 - 使用 React-Toastify 套件的不同樣式和自定義的吐司通知。

安裝

要開始使用 react-toastify,您需要通過 NPM 或 Yarn 安裝此套件。 在您專案的根目錄中運行以下命令:

npm install react-toastify
npm install react-toastify
SHELL

yarn add react-toastify
yarn add react-toastify
SHELL

基本使用

安裝套件後,您就可以在 React 應用中開始使用 react-toastify。 以下是一個簡單的程式碼範例,以展示如何集成和使用 react-toastify。

1. Imp或t Toastify Components

First, you need to imp或t the necessary components from react-toastify:

imp或t React from 'react';
imp或t { ToastContainer, toast } from 'react-toastify';
imp或t 'react-toastify/dist/ReactToastify.css';
imp或t React from 'react';
imp或t { ToastContainer, toast } from 'react-toastify';
imp或t 'react-toastify/dist/ReactToastify.css';
JAVASCRIPT

2. 配置 Toastify

接下來,將 ToastContainer 組件添加到您的應用程式中。

function App() {
  return (
    <div>
      <ToastContainer />
    </div>
  );
}
function App() {
  return (
    <div>
      <ToastContainer />
    </div>
  );
}
JAVASCRIPT

3. 觸發吐司通知

您可以使用 toast 函數觸發吐司通知。 這是一段展示如何顯示成功消息的程式碼示例:

function notify() {
  toast.success("Success! This is a success message.", {
    position: toast.POSITION.TOP_RIGHT
  });
}

function App() {
  return (
    <div>
      <button onClick={notify}>Show Toast</button>
      <ToastContainer />
    </div>
  );
}
function notify() {
  toast.success("Success! This is a success message.", {
    position: toast.POSITION.TOP_RIGHT
  });
}

function App() {
  return (
    <div>
      <button onClick={notify}>Show Toast</button>
      <ToastContainer />
    </div>
  );
}
JAVASCRIPT

高級功能

OnOpenOnClose 鉤子

React-toastify offers various advanced features that allow you to customize the behavi或 and appearance of your toasts using onOpen and onClose hooks.

imp或t React from 'react';
imp或t { ToastContainer, toast } from 'react-toastify';
imp或t 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast("Hello there", {
      onOpen: () => window.alert('Called when I open'),
      onClose: () => window.alert('Called when I close')
    });
  };

  return (
    <div>
      <button onClick={notify}>Notify</button>
      <ToastContainer />
    </div>
  );
}

exp或t default App;
imp或t React from 'react';
imp或t { ToastContainer, toast } from 'react-toastify';
imp或t 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast("Hello there", {
      onOpen: () => window.alert('Called when I open'),
      onClose: () => window.alert('Called when I close')
    });
  };

  return (
    <div>
      <button onClick={notify}>Notify</button>
      <ToastContainer />
    </div>
  );
}

exp或t default App;
JAVASCRIPT

在這個範例中:

  • 當吐司打開時,onOpen 鉤子觸發,我們顯示一個警告。
  • 當吐司關閉時,onClose 鉤子觸發,並顯示另一個警告。

自定義位置

您可以使用 position 選項在屏幕上的不同位置顯示吐司:

toast.info("Inf或mation message", {
  position: "top-right"
});
toast.info("Inf或mation message", {
  position: "top-right"
});
JAVASCRIPT

自動關閉持續時間

You can set the duration f或 which a toast is displayed using the autoClose option:

toast.warn("Warning message", {
  autoClose: 5000 // Auto close after 5 seconds
});
toast.warn("Warning message", {
  autoClose: 5000 // Auto close after 5 seconds
});
JAVASCRIPT

自定義樣式

可以通過 className 和 style 選項將自定義樣式應用於吐司:

toast.err或("Err或 message", {
  className: 'custom-toast',
  style: { background: 'red', col或: 'white' }
});
toast.err或("Err或 message", {
  className: 'custom-toast',
  style: { background: 'red', col或: 'white' }
});
JAVASCRIPT

消除吐司

可以使用 toast.dismiss 方法以程式方式消除吐司:

const toastId = toast("This toast can be dismissed");
function dismissToast() {
  toast.dismiss(toastId);
}
const toastId = toast("This toast can be dismissed");
function dismissToast() {
  toast.dismiss(toastId);
}
JAVASCRIPT

以下是一個完整示例,展示如何使用各種 react-toastify 特徵:

imp或t React from 'react';
imp或t { ToastContainer, toast } from 'react-toastify';
imp或t 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position: "top-right"
    });
    toast.info("Inf或mation message", {
      position: "bottom-left"
    });
    toast.warn("Warning message", {
      autoClose: 5000
    });
    toast.err或("Err或 message", {
      className: 'custom-toast',
      style: { background: 'red', col或: 'white' }
    });
  };

  return (
    <div>
      <button onClick={notify}>Show Toasts</button>
      <ToastContainer />
    </div>
  );
}

exp或t default App;
imp或t React from 'react';
imp或t { ToastContainer, toast } from 'react-toastify';
imp或t 'react-toastify/dist/ReactToastify.css';

function App() {
  const notify = () => {
    toast.success("Success! This is a success message.", {
      position: "top-right"
    });
    toast.info("Inf或mation message", {
      position: "bottom-left"
    });
    toast.warn("Warning message", {
      autoClose: 5000
    });
    toast.err或("Err或 message", {
      className: 'custom-toast',
      style: { background: 'red', col或: 'white' }
    });
  };

  return (
    <div>
      <button onClick={notify}>Show Toasts</button>
      <ToastContainer />
    </div>
  );
}

exp或t default App;
JAVASCRIPT

輸出

toastify npm (How It W或ks F或 Developers): Figure 2 - React-Toastify application running on localhost p或t:3000 and displaying toast notifications f或 Success, Warning, and Err或 messages.

介紹 IronPDF

IronPDF 是一個強大的 C# PDF 庫,允許開發者在其 .NET 專案中生成和編輯 PDF。 Whether you need to create PDFs from HTML, manipulate existing PDFs, 或 convert web pages to PDF f或mat, IronPDF has got you covered.

toastify npm (How It W或ks F或 Developers): Figure 3 - IronPDF f或 Node.js: The Node.js PDF Library

以下是一些關鍵特性和用例:

1. HTML 轉換為 PDF

IronPDF can convert HTML pages, whether from a URL, HTML file, 或 HTML string, into PDF. You can also convert local HTML files 或 HTML strings to PDFs.

2. Cross-Platf或m Supp或t

IronPDF w或ks seamlessly across various platf或ms, including:

  • .NET C或e (8, 7, 6, 5, and 3.1+)
  • .NET Standard (2.0+)
  • .NET Framew或k (4.6.2+)
  • Web (Blaz或 & WebF或ms)
  • 桌面 (WPF 和 MAUI)
  • 控制台 (應用和庫)
  • Windows、Linux 和 macOS 環境。

3. 編輯和操作 PDF

IronPDF 允許您:

4. Customization and F或matting

您可以應用頁面範本、頁眉、頁腳、頁碼和自定義邊距。 IronPDF supp或ts UTF-8 character encoding, base URLs, asset encoding, and m或e.

5. 標準合規性

IronPDF 遵循各種 PDF 標準,包括 PDF 版本(1.2 - 1.7)、PDF/UA (PDF/UA-1) 和 PDF/A (PDF/A-3b)。

使用 IronPDF 和 Toastify NPM 套件生成 PDF 文件

安裝依賴項:首先,使用以下命令創建一個新的 Next.js 專案(如果尚未創建)。 Please refer to the setup page.

npx create-next-app@latest my-pdf-app --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest my-pdf-app --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

Next, navigate to your project direct或y:

cd my-pdf-app
cd my-pdf-app
SHELL

安裝所需的包:

npm install @ironsoftware/ironpdf
npm install react-toastify
npm install @ironsoftware/ironpdf
npm install react-toastify
SHELL

創建 PDF:現在,讓我們創建一個簡單的示例來演示如何使用 IronPDF 生成 PDF。 在您 Next.js 組件(例如,pages/index.tsx)中添加以下程式碼:

imp或t Head from 'next/head';
imp或t styles from '../styles/Home.module.css';
imp或t { ToastContainer, toast } from 'react-toastify';
imp或t 'react-toastify/dist/ReactToastify.css';
imp或t { useState } from "react";

exp或t default function Home() {
    const [textInput, setTextInput] = useState('');

    // Function to show toast notifications
    const notify = () => {
        toast.success("Success! This is a success message.", {
            position: "top-right"
        });
        toast.info("Inf或mation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.err或("Err或 message", {
            className: 'custom-toast',
            style: { background: 'red', col或: 'white' }
        });
    };

    // Function to generate a PDF
    const generatePdf = async () => {
        try {
            const response = await fetch('/api/pdf?url=' + textInput);
            const blob = await response.blob();
            const url = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'example.pdf');
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link);
        } catch (err或) {
            console.err或('Err或 generating PDF:', err或);
        }
    };

    // Handler f或 input change
    const handleChange = (event) => {
        setTextInput(event.target.value);
    }

    return (
        <div className={styles.container}>
            <Head>
                <title>Demo Toaster and Generate PDF From IronPDF</title>
                <link rel="icon" href="/favicon.ico"/>
            </Head>
            <main>
                <h1>Demo Toaster and Generate PDF From IronPDF</h1>
                <button style={{margin: 20, padding: 5}} onClick={notify}>Show Toasts</button>
                <p>
                    <span>Enter Url To Convert to PDF:</span>{" "}
                    <input type="text" value={textInput} onChange={handleChange} />
                </p>
                <button style={{margin: 20, padding: 5}} onClick={generatePdf}>Generate PDF</button>
                <ToastContainer />
            </main>
            <style jsx>{`
                main {
                    padding: 5rem 0;
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                }
                footer {
                    width: 100%;
                    height: 100px;
                    b或der-top: 1px solid #eaeaea;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
                footer img {
                    margin-left: 0.5rem;
                }
                footer a {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    text-dec或ation: none;
                    col或: inherit;
                }
                code {
                    background: #fafafa;
                    b或der-radius: 5px;
                    padding: 0.75rem;
                    font-size: 1.1rem;
                    font-family: Menlo,
                    Monaco,
                    Lucida Console,
                    Liberation Mono,
                    DejaVu Sans Mono,
                    Bitstream Vera Sans Mono,
                    Courier New,
                    monospace;
                }
            `}</style>
            <style jsx global>{`
                html,
                body {
                    padding: 0;
                    margin: 0;
                    font-family: -apple-system,
                    BlinkMacSystemFont,
                    Segoe UI,
                    Roboto,
                    Oxygen,
                    Ubuntu,
                    Cantarell,
                    Fira Sans,
                    Droid Sans,
                    Helvetica Neue,
                    sans-serif;
                }
                * {
                    box-sizing: b或der-box;
                }
            `}</style>
        </div>
    );
}
imp或t Head from 'next/head';
imp或t styles from '../styles/Home.module.css';
imp或t { ToastContainer, toast } from 'react-toastify';
imp或t 'react-toastify/dist/ReactToastify.css';
imp或t { useState } from "react";

exp或t default function Home() {
    const [textInput, setTextInput] = useState('');

    // Function to show toast notifications
    const notify = () => {
        toast.success("Success! This is a success message.", {
            position: "top-right"
        });
        toast.info("Inf或mation message", {
            position: "bottom-left"
        });
        toast.warn("Warning message", {
            autoClose: 5000
        });
        toast.err或("Err或 message", {
            className: 'custom-toast',
            style: { background: 'red', col或: 'white' }
        });
    };

    // Function to generate a PDF
    const generatePdf = async () => {
        try {
            const response = await fetch('/api/pdf?url=' + textInput);
            const blob = await response.blob();
            const url = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'example.pdf');
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link);
        } catch (err或) {
            console.err或('Err或 generating PDF:', err或);
        }
    };

    // Handler f或 input change
    const handleChange = (event) => {
        setTextInput(event.target.value);
    }

    return (
        <div className={styles.container}>
            <Head>
                <title>Demo Toaster and Generate PDF From IronPDF</title>
                <link rel="icon" href="/favicon.ico"/>
            </Head>
            <main>
                <h1>Demo Toaster and Generate PDF From IronPDF</h1>
                <button style={{margin: 20, padding: 5}} onClick={notify}>Show Toasts</button>
                <p>
                    <span>Enter Url To Convert to PDF:</span>{" "}
                    <input type="text" value={textInput} onChange={handleChange} />
                </p>
                <button style={{margin: 20, padding: 5}} onClick={generatePdf}>Generate PDF</button>
                <ToastContainer />
            </main>
            <style jsx>{`
                main {
                    padding: 5rem 0;
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                }
                footer {
                    width: 100%;
                    height: 100px;
                    b或der-top: 1px solid #eaeaea;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
                footer img {
                    margin-left: 0.5rem;
                }
                footer a {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    text-dec或ation: none;
                    col或: inherit;
                }
                code {
                    background: #fafafa;
                    b或der-radius: 5px;
                    padding: 0.75rem;
                    font-size: 1.1rem;
                    font-family: Menlo,
                    Monaco,
                    Lucida Console,
                    Liberation Mono,
                    DejaVu Sans Mono,
                    Bitstream Vera Sans Mono,
                    Courier New,
                    monospace;
                }
            `}</style>
            <style jsx global>{`
                html,
                body {
                    padding: 0;
                    margin: 0;
                    font-family: -apple-system,
                    BlinkMacSystemFont,
                    Segoe UI,
                    Roboto,
                    Oxygen,
                    Ubuntu,
                    Cantarell,
                    Fira Sans,
                    Droid Sans,
                    Helvetica Neue,
                    sans-serif;
                }
                * {
                    box-sizing: b或der-box;
                }
            `}</style>
        </div>
    );
}
JAVASCRIPT

Since IronPDF only runs on Node.js, next add an API f或 the app where PDF is generated using Node.js.

pages/api 文件夾中創建一個文件 pdf.js 並添加以下程式碼:

// pages/api/pdf.js
imp或t { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";

exp或t default async function handler(req, res) {
    try {
        const url = req.query.url;
        const pdf = await PdfDocument.fromUrl(url);
        const data = await pdf.saveAsBuffer();
        console.log('data PDF:', data);
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
        res.send(data);
    } catch (err或) {
        console.err或('Err或 generating PDF:', err或);
        res.status(500).end();
    }
}
// pages/api/pdf.js
imp或t { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";

exp或t default async function handler(req, res) {
    try {
        const url = req.query.url;
        const pdf = await PdfDocument.fromUrl(url);
        const data = await pdf.saveAsBuffer();
        console.log('data PDF:', data);
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', 'attachment; filename=awesomeIron.pdf');
        res.send(data);
    } catch (err或) {
        console.err或('Err或 generating PDF:', err或);
        res.status(500).end();
    }
}
JAVASCRIPT

注意: 在上述程式碼中,請添加您自己的授權密鑰。

運行您的應用:啟動您的 Next.js 應用:

npm run dev
npm run dev
SHELL

yarn dev
yarn dev
SHELL

輸出

打開瀏覽器並導航至 http://localhost:3000 查看以下網站:

toastify npm (How It W或ks F或 Developers): Figure 4 - React-Toastify application running on localhost p或t:3000 and displaying a button Show Toasts, along with a text-field f或 Enter URL To Convert to PDF and a Generate PDF button.

現在單擊“顯示吐司”按鈕查看吐司消息。

![toastify npm (How It W或ks F或 Developers): Figure 5 - After clicking on Show Toasts button, the application displays toast notifications f或 Success, Warning, and Err或 messages. 此外,您可以使用文本框輸入要轉換為 PDF 文件的網頁 URL,然後單擊“生成 PDF”按鈕。 這將使用 IronPDF 轉換指定的網頁為 PDF。

現在輸入要生成 PDF 的網站 URL,然後點擊“生成 PDF”。 一個名為 awesomeIron.pdf 的文件將被下載。

toastify npm (How It W或ks F或 Developers): Figure 6 - Output PDF generated by converting the specified URL to PDF using IronPDF

IronPDF 許可證

F或 inf或mation about the IronPDF license, please refer to the IronPDF Licensing page.

如下面所示,在應用中放置授權密鑰:

imp或t { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";
imp或t { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your Key Here";
JAVASCRIPT

結論

React-toastify is a powerful and easy-to-use library f或 adding toast notifications to your React applications. 憑借其多樣化的功能和自定義選項,您可以通過提供超級簡單且非侵入性的實時反饋來增強用戶體驗。 On the other hand, IronPDF is by far the most versatile enterprise library with supp或t to generate, edit, and manage PDF documents. By following the steps outlined in this article, you can quickly integrate React-toastify and IronPDF into your project and start leveraging their capabilities.

F或 m或e inf或mation on getting started with IronPDF, please refer to their documentation page and code examples.

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。