跳至页脚内容
NODE 帮助

toastify npm(开发者如何使用)

在现代网页开发中,为用户提供及时反馈对于一个流畅的用户体验至关重要。 快速通知是一种有效的方式,可以在不打扰用户工作流程的情况下传递信息。 由于其简单性和灵活性,React-toastify 包是实现 React 应用程序中快速通知的热门选择。 我们还将查看 IronPDF NPM 包,以生成、编辑和管理 PDF 文档。 本文将指导您在 React 项目中集成 React-toastifyIronPDF 的过程。

什么是 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. 导入 Toastify 组件

首先,您需要从 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 提供了多种高级功能,允许您使用 onOpenonClose 钩子自定义快速通知的行为和外观。

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

自动关闭时长

您可以使用 autoClose 选项设置快速通知显示的时长:

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(开发人员如何使用):图2 - 在 localhost 端口:3000 上运行的 React-Toastify 应用程序, 显示成功、警告和错误消息的快速通知。

IronPDF 简介

IronPDF 是一个强大的 C# PDF 库,允许开发人员在他们的 .NET 项目中生成和编辑 PDF。 无论您需要从 HTML 创建 PDF、操作现有 PDF,还是将网页转换为 PDF 格式,IronPDF 都能满足您的需求。

toastify NPM(开发人员如何使用):图3 - IronPDF f或 Node.js: Node.js PDF 库

以下是一些关键特性和用例:

1. HTML 到 PDF 转换

IronPDF 可以将 HTML 页面,无论是来自 URL、HTML 文件还是 HTML 字符串,转换为 PDF。 您还可以将本地 HTML 文件或 HTML 字符串转换为 PDF。

2. 跨平台支持

IronPDF 无缝支持各种平台,包括:

  • .NET C或e (8, 7, 6, 5, 和 3.1+)
  • .NET Standard (2.0+)
  • .NET Framew或k (4.6.2+)
  • 网络 (Blaz或 & WebF或ms)
  • 桌面 (WPF & MAUI)
  • 控制台 (应用程序 & 库)
  • Windows、Linux 和 macOS 环境。

3. 编辑和操作 PDF

IronPDF 允许您:

4. 自定义和格式化

您可以应用页面模板、页眉、页脚、页码和自定义边距。 IronPDF 支持 UTF-8 字符编码、基础 URL、资源编码等。

5. 标准合规性

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

使用 IronPDF 和 Toastify NPM 包生成 PDF 文档

安装依赖:首先,使用以下命令创建一个新的Next.js项目(如果还没有创建)。 请参阅 设置页面。

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

接下来,导航到您的项目目录:

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

由于 IronPDF 仅在 Node.js 上运行,接下来为应用程序添加一个 API,在 Node.js 中生成 PDF。

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(开发人员如何使用):图4 - 在 localhost 端口:3000 上运行的 React-Toastify 应用程序,显示显示快速通知按钮、一个输入要转换为 PDF 的 URL文本框和一个生成 PDF按钮。

现在点击"显示快速通知"按钮查看快速消息。

toastify NPM(开发人员如何使用):图5 - 点击显示快速通知按钮后,应用程序显示成功、警告和错误消息的快速通知。 此外,您可以使用文本框输入要转换为 PDF 文档的网页 URL,并点击"生成 PDF"按钮。 这将使用 IronPDF 转换指定的网页为 PDF。

现在输入一个网站 URL 以生成 PDF,然后点击"生成 PDF"。 一个名为 awesomeIron.pdf 的文件将被下载。

toastify NPM(开发人员如何使用):图6 - 使用 IronPDF 将指定 URL 转换为 PDF 生成的输出 PDF

IronPDF 许可证

关于 IronPDF 许可证的信息,请参阅 IronPDF 许可证 页面。

在应用程序中将许可证密钥放置如下所示:

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 是一个功能强大且易于使用的库,用于向您的 React 应用程序添加快速通知。 凭借其广泛的功能和自定义选项,您可以通过提供实时反馈以简单而非侵入性的方式增强用户体验。 另一方面,IronPDF 是目前支持生成、编辑和管理 PDF 文档的最通用的企业库。 通过遵循本文中概述的步骤,您可以快速将 React-toastifyIronPDF 集成到项目中,并开始利用它们的功能。

有关 IronPDF 入门的更多信息,请参阅其 文档 页面和 代码示例

Darrius Serrant
全栈软件工程师(WebOps)

Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。

在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。

对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。