reactjs - 我如何使用 hook 中的 react-toastify?

标签 reactjs react-hooks react-toastify

我找到了 useToastuseToastContainer,但是缺少文档,我不明白如何使用这些 Hook 。任何人都可以提供有关这些 Hook 的一些信息吗?

最佳答案

toasts 继承了 ToastContainer 的 属性。在 toast 上定义的 Prop 取代了 ToastContainer 的 Prop 。

您可以通过两种方式在您的应用程序中使用toasts:

1. Define ToastContainer inside the component

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
  
  const App = () => {
    notify = () => toast("Wow so easy !");

    return (
      <div>
        <button onClick={notify}>Notify !</button>

        // You can add <ToastContainer /> in root component as well.
        <ToastContainer />
      </div>
    );
  }

2. Call toast.configure() once in your app. At the root of your app is the best place.

如果没有挂载,该库将为您挂载一个 ToastContainer

import { toast } from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
  
   // Call it once in your app. At the root of your app is the best place
  toast.configure()
  
  const App = () => {
    notify = () => toast("Wow so easy !");

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

您可以使用其中任何一个。我更喜欢 2nd 方法,因为您只需要定义 toast.configure(),这是一种非常简洁的添加方法。

You can add configuration as per your need like below:

toast.configure({
  autoClose: 8000,
  draggable: false,
  //etc you get the idea
});

编辑

如果您想使用 toast Hook ,则必须使用 ToastProvider 包装您的应用,以便在您应用的其他地方访问它的上下文。

import { ToastProvider, useToasts } from 'react-toast-notifications'

const FormWithToasts = () => {
  const { addToast } = useToasts()

  const onSubmit = async value => {
    const { error } = await dataPersistenceLayer(value)

    if (error) {
      addToast(error.message, { appearance: 'error' })
    } else {
      addToast('Saved Successfully', { appearance: 'success' })
    }
  }

  return <form onSubmit={onSubmit}>...</form>
}

const App = () => (
  <ToastProvider>
    <FormWithToasts />
  </ToastProvider>
)

关于reactjs - 我如何使用 hook 中的 react-toastify?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62820758/

相关文章:

javascript - Facebook 登录不适用于 hello.js

javascript - 如何使用 FilePicker 从 'react-file-picker' 在 React 中显示用户上传的 PDF?

javascript - 如何防止在 React 中使用钩子(Hook)重新呈现页面?

reactjs - 关于useEffect中的无限循环

javascript - 如何同步React中不同组件的身份验证状态?

javascript - 中间组件逻辑仅在 React 中应用一次

javascript - React-toastify 显示多个 toast

javascript - 如何使用useSelector访问函数组件中redux的存储状态变量?

javascript - 在 React-Toastify 消息中添加 Material 图标