跳至页脚内容
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 钩子触发,并显示另一个提示。

自定义位置

您可以使用位置选项在屏幕上的不同位置显示快速通知:

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 和样式选项为快速通知应用自定义样式:

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。

现在输入一个网站 URL 以生成 PDF,然后点击“生成 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 来说,他的工作令人满意,因为它被重视并产生真正的影响。